Search in sources :

Example 6 with PKIXExtendedParameters

use of com.github.zhenwei.provider.jcajce.PKIXExtendedParameters in project LinLong-Java by zhenwei1108.

the class PKIXAttrCertPathValidatorSpi method engineValidate.

/**
 * Validates an attribute certificate with the given certificate path.
 *
 * <p>
 * <code>params</code> must be an instance of
 * <code>ExtendedPKIXParameters</code>.
 * <p>
 * The target constraints in the <code>params</code> must be an
 * <code>X509AttributeCertStoreSelector</code> with at least the attribute
 * certificate criterion set. Obey that also target informations may be necessary to correctly
 * validate this attribute certificate.
 * <p>
 * The attribute certificate issuer must be added to the trusted attribute issuers with {@link
 * com.github.zhenwei.provider.x509.ExtendedPKIXParameters#setTrustedACIssuers(Set)}.
 *
 * @param certPath The certificate path which belongs to the attribute certificate issuer public
 *                 key certificate.
 * @param params   The PKIX parameters.
 * @return A <code>PKIXCertPathValidatorResult</code> of the result of validating the
 * <code>certPath</code>.
 * @throws InvalidAlgorithmParameterException if <code>params</code> is inappropriate for this
 *                                            validator.
 * @throws CertPathValidatorException         if the verification fails.
 */
public CertPathValidatorResult engineValidate(CertPath certPath, CertPathParameters params) throws CertPathValidatorException, InvalidAlgorithmParameterException {
    if (!(params instanceof ExtendedPKIXParameters || params instanceof PKIXExtendedParameters)) {
        throw new InvalidAlgorithmParameterException("Parameters must be a " + ExtendedPKIXParameters.class.getName() + " instance.");
    }
    Set attrCertCheckers = new HashSet();
    Set prohibitedACAttrbiutes = new HashSet();
    Set necessaryACAttributes = new HashSet();
    Set trustedACIssuers = new HashSet();
    PKIXExtendedParameters paramsPKIX;
    if (params instanceof PKIXParameters) {
        PKIXExtendedParameters.Builder paramsPKIXBldr = new PKIXExtendedParameters.Builder((PKIXParameters) params);
        if (params instanceof ExtendedPKIXParameters) {
            ExtendedPKIXParameters extPKIX = (ExtendedPKIXParameters) params;
            paramsPKIXBldr.setUseDeltasEnabled(extPKIX.isUseDeltasEnabled());
            paramsPKIXBldr.setValidityModel(extPKIX.getValidityModel());
            attrCertCheckers = extPKIX.getAttrCertCheckers();
            prohibitedACAttrbiutes = extPKIX.getProhibitedACAttributes();
            necessaryACAttributes = extPKIX.getNecessaryACAttributes();
        }
        paramsPKIX = paramsPKIXBldr.build();
    } else {
        paramsPKIX = (PKIXExtendedParameters) params;
    }
    final Date currentDate = new Date();
    final Date validityDate = CertPathValidatorUtilities.getValidityDate(paramsPKIX, currentDate);
    Selector certSelect = paramsPKIX.getTargetConstraints();
    if (!(certSelect instanceof X509AttributeCertStoreSelector)) {
        throw new InvalidAlgorithmParameterException("TargetConstraints must be an instance of " + X509AttributeCertStoreSelector.class.getName() + " for " + this.getClass().getName() + " class.");
    }
    X509AttributeCertificate attrCert = ((X509AttributeCertStoreSelector) certSelect).getAttributeCert();
    CertPath holderCertPath = RFC3281CertPathUtilities.processAttrCert1(attrCert, paramsPKIX);
    CertPathValidatorResult result = RFC3281CertPathUtilities.processAttrCert2(certPath, paramsPKIX);
    X509Certificate issuerCert = (X509Certificate) certPath.getCertificates().get(0);
    RFC3281CertPathUtilities.processAttrCert3(issuerCert, paramsPKIX);
    RFC3281CertPathUtilities.processAttrCert4(issuerCert, trustedACIssuers);
    RFC3281CertPathUtilities.processAttrCert5(attrCert, validityDate);
    // 6 already done in X509AttributeCertStoreSelector
    RFC3281CertPathUtilities.processAttrCert7(attrCert, certPath, holderCertPath, paramsPKIX, attrCertCheckers);
    RFC3281CertPathUtilities.additionalChecks(attrCert, prohibitedACAttrbiutes, necessaryACAttributes);
    RFC3281CertPathUtilities.checkCRLs(attrCert, paramsPKIX, currentDate, validityDate, issuerCert, certPath.getCertificates(), helper);
    return result;
}
Also used : InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) Set(java.util.Set) HashSet(java.util.HashSet) X509AttributeCertStoreSelector(com.github.zhenwei.provider.x509.X509AttributeCertStoreSelector) X509AttributeCertificate(com.github.zhenwei.provider.x509.X509AttributeCertificate) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate) PKIXExtendedParameters(com.github.zhenwei.provider.jcajce.PKIXExtendedParameters) ExtendedPKIXParameters(com.github.zhenwei.provider.x509.ExtendedPKIXParameters) ExtendedPKIXParameters(com.github.zhenwei.provider.x509.ExtendedPKIXParameters) PKIXParameters(java.security.cert.PKIXParameters) CertPath(java.security.cert.CertPath) CertPathValidatorResult(java.security.cert.CertPathValidatorResult) HashSet(java.util.HashSet) X509AttributeCertStoreSelector(com.github.zhenwei.provider.x509.X509AttributeCertStoreSelector) Selector(com.github.zhenwei.core.util.Selector)

Example 7 with PKIXExtendedParameters

use of com.github.zhenwei.provider.jcajce.PKIXExtendedParameters in project LinLong-Java by zhenwei1108.

the class PKIXCertPathValidatorSpi_8 method engineValidate.

public CertPathValidatorResult engineValidate(CertPath certPath, CertPathParameters params) throws CertPathValidatorException, InvalidAlgorithmParameterException {
    PKIXExtendedParameters paramsPKIX;
    if (params instanceof PKIXParameters) {
        PKIXExtendedParameters.Builder paramsPKIXBldr = new PKIXExtendedParameters.Builder((PKIXParameters) params);
        if (params instanceof ExtendedPKIXParameters) {
            ExtendedPKIXParameters extPKIX = (ExtendedPKIXParameters) params;
            paramsPKIXBldr.setUseDeltasEnabled(extPKIX.isUseDeltasEnabled());
            paramsPKIXBldr.setValidityModel(extPKIX.getValidityModel());
        }
        paramsPKIX = paramsPKIXBldr.build();
    } else if (params instanceof PKIXExtendedBuilderParameters) {
        paramsPKIX = ((PKIXExtendedBuilderParameters) params).getBaseParameters();
    } else if (params instanceof PKIXExtendedParameters) {
        paramsPKIX = (PKIXExtendedParameters) params;
    } else {
        throw new InvalidAlgorithmParameterException("Parameters must be a " + PKIXParameters.class.getName() + " instance.");
    }
    if (paramsPKIX.getTrustAnchors() == null) {
        throw new InvalidAlgorithmParameterException("trustAnchors is null, this is not allowed for certification path validation.");
    }
    // 
    // 6.1.1 - inputs
    // 
    // 
    // (a)
    // 
    List certs = certPath.getCertificates();
    int n = certs.size();
    if (certs.isEmpty()) {
        throw new CertPathValidatorException("Certification path is empty.", null, certPath, -1);
    }
    // 
    // (b)
    // 
    final Date currentDate = new Date();
    final Date validityDate = CertPathValidatorUtilities.getValidityDate(paramsPKIX, currentDate);
    // 
    // (c)
    // 
    Set userInitialPolicySet = paramsPKIX.getInitialPolicies();
    // 
    // (d)
    // 
    TrustAnchor trust;
    try {
        trust = CertPathValidatorUtilities.findTrustAnchor((X509Certificate) certs.get(certs.size() - 1), paramsPKIX.getTrustAnchors(), paramsPKIX.getSigProvider());
        if (trust == null) {
            throw new CertPathValidatorException("Trust anchor for certification path not found.", null, certPath, -1);
        }
        checkCertificate(trust.getTrustedCert());
    } catch (AnnotatedException e) {
        throw new CertPathValidatorException(e.getMessage(), e.getUnderlyingException(), certPath, certs.size() - 1);
    }
    // RFC 5280 - CRLs must originate from the same trust anchor as the target certificate.
    paramsPKIX = new PKIXExtendedParameters.Builder(paramsPKIX).setTrustAnchor(trust).build();
    PKIXCertRevocationChecker revocationChecker = null;
    List pathCheckers = new ArrayList();
    Iterator certIter = paramsPKIX.getCertPathCheckers().iterator();
    while (certIter.hasNext()) {
        PKIXCertPathChecker checker = (PKIXCertPathChecker) certIter.next();
        checker.init(false);
        if (checker instanceof PKIXRevocationChecker) {
            if (revocationChecker != null) {
                throw new CertPathValidatorException("only one PKIXRevocationChecker allowed");
            }
            revocationChecker = (checker instanceof PKIXCertRevocationChecker) ? (PKIXCertRevocationChecker) checker : new WrappedRevocationChecker(checker);
        } else {
            pathCheckers.add(checker);
        }
    }
    if (paramsPKIX.isRevocationEnabled() && revocationChecker == null) {
        revocationChecker = new ProvRevocationChecker(helper);
    }
    // 
    // (e), (f), (g) are part of the paramsPKIX object.
    // 
    int index = 0;
    int i;
    // Certificate for each interation of the validation loop
    // Signature information for each iteration of the validation loop
    // 
    // 6.1.2 - setup
    // 
    // 
    // (a)
    // 
    List[] policyNodes = new ArrayList[n + 1];
    for (int j = 0; j < policyNodes.length; j++) {
        policyNodes[j] = new ArrayList();
    }
    Set policySet = new HashSet();
    policySet.add(RFC3280CertPathUtilities.ANY_POLICY);
    PKIXPolicyNode validPolicyTree = new PKIXPolicyNode(new ArrayList(), 0, policySet, null, new HashSet(), RFC3280CertPathUtilities.ANY_POLICY, false);
    policyNodes[0].add(validPolicyTree);
    // 
    // (b) and (c)
    // 
    PKIXNameConstraintValidator nameConstraintValidator = new PKIXNameConstraintValidator();
    // (d)
    // 
    int explicitPolicy;
    Set acceptablePolicies = new HashSet();
    if (paramsPKIX.isExplicitPolicyRequired()) {
        explicitPolicy = 0;
    } else {
        explicitPolicy = n + 1;
    }
    // 
    // (e)
    // 
    int inhibitAnyPolicy;
    if (paramsPKIX.isAnyPolicyInhibited()) {
        inhibitAnyPolicy = 0;
    } else {
        inhibitAnyPolicy = n + 1;
    }
    // 
    // (f)
    // 
    int policyMapping;
    if (paramsPKIX.isPolicyMappingInhibited()) {
        policyMapping = 0;
    } else {
        policyMapping = n + 1;
    }
    // 
    // (g), (h), (i), (j)
    // 
    PublicKey workingPublicKey;
    X500Name workingIssuerName;
    X509Certificate sign = trust.getTrustedCert();
    try {
        if (sign != null) {
            workingIssuerName = PrincipalUtils.getSubjectPrincipal(sign);
            workingPublicKey = sign.getPublicKey();
        } else {
            workingIssuerName = PrincipalUtils.getCA(trust);
            workingPublicKey = trust.getCAPublicKey();
        }
    } catch (RuntimeException ex) {
        throw new ExtCertPathValidatorException("Subject of trust anchor could not be (re)encoded.", ex, certPath, -1);
    }
    AlgorithmIdentifier workingAlgId = null;
    try {
        workingAlgId = CertPathValidatorUtilities.getAlgorithmIdentifier(workingPublicKey);
    } catch (CertPathValidatorException e) {
        throw new ExtCertPathValidatorException("Algorithm identifier of public key of trust anchor could not be read.", e, certPath, -1);
    }
    ASN1ObjectIdentifier workingPublicKeyAlgorithm = workingAlgId.getAlgorithm();
    ASN1Encodable workingPublicKeyParameters = workingAlgId.getParameters();
    // 
    // (k)
    // 
    int maxPathLength = n;
    if (paramsPKIX.getTargetConstraints() != null && !paramsPKIX.getTargetConstraints().match((X509Certificate) certs.get(0))) {
        throw new ExtCertPathValidatorException("Target certificate in certification path does not match targetConstraints.", null, certPath, 0);
    }
    // 
    // initialize CertPathChecker's
    // 
    X509Certificate cert = null;
    for (index = certs.size() - 1; index >= 0; index--) {
        // try
        // {
        // 
        // 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 initialized the
        // first time from the TrustAnchor
        // 
        cert = (X509Certificate) certs.get(index);
        boolean verificationAlreadyPerformed = (index == certs.size() - 1);
        try {
            checkCertificate(cert);
        } catch (AnnotatedException e) {
            throw new CertPathValidatorException(e.getMessage(), e.getUnderlyingException(), certPath, index);
        }
        // 
        // 6.1.3
        // 
        RFC3280CertPathUtilities.processCertA(certPath, paramsPKIX, validityDate, revocationChecker, index, workingPublicKey, verificationAlreadyPerformed, workingIssuerName, sign);
        RFC3280CertPathUtilities.processCertBC(certPath, index, nameConstraintValidator, isForCRLCheck);
        validPolicyTree = RFC3280CertPathUtilities.processCertD(certPath, index, acceptablePolicies, validPolicyTree, policyNodes, inhibitAnyPolicy, isForCRLCheck);
        validPolicyTree = RFC3280CertPathUtilities.processCertE(certPath, index, validPolicyTree);
        RFC3280CertPathUtilities.processCertF(certPath, index, validPolicyTree, explicitPolicy);
        // 
        if (i != n) {
            if (cert != null && cert.getVersion() == 1) {
                // we've found the trust anchor at the top of the path, ignore and keep going
                if ((i == 1) && cert.equals(trust.getTrustedCert())) {
                    continue;
                }
                throw new CertPathValidatorException("Version 1 certificates can't be used as CA ones.", null, certPath, index);
            }
            RFC3280CertPathUtilities.prepareNextCertA(certPath, index);
            validPolicyTree = RFC3280CertPathUtilities.prepareCertB(certPath, index, policyNodes, validPolicyTree, policyMapping);
            RFC3280CertPathUtilities.prepareNextCertG(certPath, index, nameConstraintValidator);
            // (h)
            explicitPolicy = RFC3280CertPathUtilities.prepareNextCertH1(certPath, index, explicitPolicy);
            policyMapping = RFC3280CertPathUtilities.prepareNextCertH2(certPath, index, policyMapping);
            inhibitAnyPolicy = RFC3280CertPathUtilities.prepareNextCertH3(certPath, index, inhibitAnyPolicy);
            // 
            // (i)
            // 
            explicitPolicy = RFC3280CertPathUtilities.prepareNextCertI1(certPath, index, explicitPolicy);
            policyMapping = RFC3280CertPathUtilities.prepareNextCertI2(certPath, index, policyMapping);
            // (j)
            inhibitAnyPolicy = RFC3280CertPathUtilities.prepareNextCertJ(certPath, index, inhibitAnyPolicy);
            // (k)
            RFC3280CertPathUtilities.prepareNextCertK(certPath, index);
            // (l)
            maxPathLength = RFC3280CertPathUtilities.prepareNextCertL(certPath, index, maxPathLength);
            // (m)
            maxPathLength = RFC3280CertPathUtilities.prepareNextCertM(certPath, index, maxPathLength);
            // (n)
            RFC3280CertPathUtilities.prepareNextCertN(certPath, index);
            Set criticalExtensions = cert.getCriticalExtensionOIDs();
            if (criticalExtensions != null) {
                criticalExtensions = new HashSet(criticalExtensions);
                // these extensions are handled by the algorithm
                criticalExtensions.remove(RFC3280CertPathUtilities.KEY_USAGE);
                criticalExtensions.remove(RFC3280CertPathUtilities.CERTIFICATE_POLICIES);
                criticalExtensions.remove(RFC3280CertPathUtilities.POLICY_MAPPINGS);
                criticalExtensions.remove(RFC3280CertPathUtilities.INHIBIT_ANY_POLICY);
                criticalExtensions.remove(RFC3280CertPathUtilities.ISSUING_DISTRIBUTION_POINT);
                criticalExtensions.remove(RFC3280CertPathUtilities.DELTA_CRL_INDICATOR);
                criticalExtensions.remove(RFC3280CertPathUtilities.POLICY_CONSTRAINTS);
                criticalExtensions.remove(RFC3280CertPathUtilities.BASIC_CONSTRAINTS);
                criticalExtensions.remove(RFC3280CertPathUtilities.SUBJECT_ALTERNATIVE_NAME);
                criticalExtensions.remove(RFC3280CertPathUtilities.NAME_CONSTRAINTS);
            } else {
                criticalExtensions = new HashSet();
            }
            // (o)
            RFC3280CertPathUtilities.prepareNextCertO(certPath, index, criticalExtensions, pathCheckers);
            // set signing certificate for next round
            sign = cert;
            // (c)
            workingIssuerName = PrincipalUtils.getSubjectPrincipal(sign);
            // (d)
            try {
                workingPublicKey = CertPathValidatorUtilities.getNextWorkingKey(certPath.getCertificates(), index, helper);
            } catch (CertPathValidatorException e) {
                throw new CertPathValidatorException("Next working key could not be retrieved.", e, certPath, index);
            }
            workingAlgId = CertPathValidatorUtilities.getAlgorithmIdentifier(workingPublicKey);
            // (f)
            workingPublicKeyAlgorithm = workingAlgId.getAlgorithm();
            // (e)
            workingPublicKeyParameters = workingAlgId.getParameters();
        }
    }
    // 
    // 6.1.5 Wrap-up procedure
    // 
    explicitPolicy = RFC3280CertPathUtilities.wrapupCertA(explicitPolicy, cert);
    explicitPolicy = RFC3280CertPathUtilities.wrapupCertB(certPath, index + 1, explicitPolicy);
    // 
    // (c) (d) and (e) are already done
    // 
    // 
    // (f)
    // 
    Set criticalExtensions = cert.getCriticalExtensionOIDs();
    if (criticalExtensions != null) {
        criticalExtensions = new HashSet(criticalExtensions);
        // these extensions are handled by the algorithm
        criticalExtensions.remove(RFC3280CertPathUtilities.KEY_USAGE);
        criticalExtensions.remove(RFC3280CertPathUtilities.CERTIFICATE_POLICIES);
        criticalExtensions.remove(RFC3280CertPathUtilities.POLICY_MAPPINGS);
        criticalExtensions.remove(RFC3280CertPathUtilities.INHIBIT_ANY_POLICY);
        criticalExtensions.remove(RFC3280CertPathUtilities.ISSUING_DISTRIBUTION_POINT);
        criticalExtensions.remove(RFC3280CertPathUtilities.DELTA_CRL_INDICATOR);
        criticalExtensions.remove(RFC3280CertPathUtilities.POLICY_CONSTRAINTS);
        criticalExtensions.remove(RFC3280CertPathUtilities.BASIC_CONSTRAINTS);
        criticalExtensions.remove(RFC3280CertPathUtilities.SUBJECT_ALTERNATIVE_NAME);
        criticalExtensions.remove(RFC3280CertPathUtilities.NAME_CONSTRAINTS);
        criticalExtensions.remove(RFC3280CertPathUtilities.CRL_DISTRIBUTION_POINTS);
        criticalExtensions.remove(Extension.extendedKeyUsage.getId());
    } else {
        criticalExtensions = new HashSet();
    }
    RFC3280CertPathUtilities.wrapupCertF(certPath, index + 1, pathCheckers, criticalExtensions);
    PKIXPolicyNode intersection = RFC3280CertPathUtilities.wrapupCertG(certPath, paramsPKIX, userInitialPolicySet, index + 1, policyNodes, validPolicyTree, acceptablePolicies);
    if ((explicitPolicy > 0) || (intersection != null)) {
        return new PKIXCertPathValidatorResult(trust, intersection, cert.getPublicKey());
    }
    throw new CertPathValidatorException("Path processing failed on policy.", null, certPath, index);
}
Also used : PKIXCertRevocationChecker(com.github.zhenwei.provider.jcajce.PKIXCertRevocationChecker) HashSet(java.util.HashSet) Set(java.util.Set) ArrayList(java.util.ArrayList) X500Name(com.github.zhenwei.core.asn1.x500.X500Name) AlgorithmIdentifier(com.github.zhenwei.core.asn1.x509.AlgorithmIdentifier) ExtendedPKIXParameters(com.github.zhenwei.provider.x509.ExtendedPKIXParameters) PKIXParameters(java.security.cert.PKIXParameters) PKIXExtendedBuilderParameters(com.github.zhenwei.provider.jcajce.PKIXExtendedBuilderParameters) PKIXCertPathChecker(java.security.cert.PKIXCertPathChecker) Iterator(java.util.Iterator) ArrayList(java.util.ArrayList) List(java.util.List) ASN1Encodable(com.github.zhenwei.core.asn1.ASN1Encodable) HashSet(java.util.HashSet) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) PublicKey(java.security.PublicKey) TrustAnchor(java.security.cert.TrustAnchor) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate) BCX509Certificate(com.github.zhenwei.provider.jcajce.interfaces.BCX509Certificate) 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) ExtendedPKIXParameters(com.github.zhenwei.provider.x509.ExtendedPKIXParameters) PKIXCertPathValidatorResult(java.security.cert.PKIXCertPathValidatorResult) PKIXRevocationChecker(java.security.cert.PKIXRevocationChecker) ASN1ObjectIdentifier(com.github.zhenwei.core.asn1.ASN1ObjectIdentifier)

Example 8 with PKIXExtendedParameters

use of com.github.zhenwei.provider.jcajce.PKIXExtendedParameters in project LinLong-Java by zhenwei1108.

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         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, PKIXExtendedParameters paramsPKIX, List certPathCerts, JcaJceHelper helper) throws AnnotatedException {
    // (f)
    // get issuer from CRL
    X509CertSelector certSelector = new X509CertSelector();
    try {
        byte[] issuerPrincipal = crl.getIssuerX500Principal().getEncoded();
        certSelector.setSubject(issuerPrincipal);
    } catch (IOException e) {
        throw new AnnotatedException("subject criteria for certificate selector to find issuer certificate for CRL could not be set", e);
    }
    PKIXCertStoreSelector selector = new PKIXCertStoreSelector.Builder(certSelector).build();
    // get CRL signing certs
    LinkedHashSet coll = new LinkedHashSet();
    try {
        RevocationUtilities.findCertificates(coll, selector, paramsPKIX.getCertificateStores());
        RevocationUtilities.findCertificates(coll, selector, paramsPKIX.getCertStores());
    } catch (AnnotatedException e) {
        throw new AnnotatedException("Issuer certificate for CRL cannot be searched.", e);
    }
    coll.add(defaultCRLSignCert);
    List validCerts = new ArrayList();
    List validKeys = new ArrayList();
    Iterator cert_it = coll.iterator();
    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 = helper.createCertPathBuilder("PKIX");
            X509CertSelector tmpCertSelector = new X509CertSelector();
            tmpCertSelector.setCertificate(signingCert);
            PKIXExtendedParameters.Builder paramsBuilder = new PKIXExtendedParameters.Builder(paramsPKIX).setTargetConstraints(new PKIXCertStoreSelector.Builder(tmpCertSelector).build());
            /*
         * 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)) {
                paramsBuilder.setRevocationEnabled(false);
            } else {
                paramsBuilder.setRevocationEnabled(true);
            }
            PKIXExtendedBuilderParameters extParams = new PKIXExtendedBuilderParameters.Builder(paramsBuilder.build()).build();
            List certs = builder.build(extParams).getCertPath().getCertificates();
            validCerts.add(signingCert);
            validKeys.add(RevocationUtilities.getNextWorkingKey(certs, 0, helper));
        } catch (CertPathBuilderException e) {
            throw new AnnotatedException("CertPath for CRL signer failed to validate.", e);
        } catch (CertPathValidatorException e) {
            throw new AnnotatedException("Public key of issuer certificate of CRL could not be retrieved.", e);
        } catch (Exception e) {
            throw new AnnotatedException(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 <= CRL_SIGN || !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 : LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) Set(java.util.Set) CertPathBuilder(java.security.cert.CertPathBuilder) ArrayList(java.util.ArrayList) X509CertSelector(java.security.cert.X509CertSelector) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) CertPathBuilderException(java.security.cert.CertPathBuilderException) CertPathValidatorException(java.security.cert.CertPathValidatorException) IOException(java.io.IOException) DistributionPoint(com.github.zhenwei.core.asn1.x509.DistributionPoint) IssuingDistributionPoint(com.github.zhenwei.core.asn1.x509.IssuingDistributionPoint) CRLDistPoint(com.github.zhenwei.core.asn1.x509.CRLDistPoint) PKIXCertStoreSelector(com.github.zhenwei.provider.jcajce.PKIXCertStoreSelector) CertPathValidatorException(java.security.cert.CertPathValidatorException) PKIXExtendedParameters(com.github.zhenwei.provider.jcajce.PKIXExtendedParameters) PKIXExtendedBuilderParameters(com.github.zhenwei.provider.jcajce.PKIXExtendedBuilderParameters) CertPathBuilderException(java.security.cert.CertPathBuilderException) Iterator(java.util.Iterator) ArrayList(java.util.ArrayList) List(java.util.List) CertPathBuilder(java.security.cert.CertPathBuilder) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

Example 9 with PKIXExtendedParameters

use of com.github.zhenwei.provider.jcajce.PKIXExtendedParameters in project LinLong-Java by zhenwei1108.

the class X509RevocationChecker method check.

public void check(Certificate certificate, Collection<String> collection) throws CertPathValidatorException {
    X509Certificate cert = (X509Certificate) certificate;
    if (isCheckEEOnly && cert.getBasicConstraints() != -1) {
        this.workingIssuerName = cert.getSubjectX500Principal();
        this.workingPublicKey = cert.getPublicKey();
        this.signingCert = cert;
        return;
    }
    TrustAnchor trustAnchor = null;
    if (workingIssuerName == null) {
        this.workingIssuerName = cert.getIssuerX500Principal();
        for (Iterator it = trustAnchors.iterator(); it.hasNext(); ) {
            TrustAnchor anchor = (TrustAnchor) it.next();
            if (workingIssuerName.equals(anchor.getCA()) || workingIssuerName.equals(anchor.getTrustedCert().getSubjectX500Principal())) {
                trustAnchor = anchor;
            }
        }
        if (trustAnchor == null) {
            throw new CertPathValidatorException("no trust anchor found for " + workingIssuerName);
        }
        this.signingCert = trustAnchor.getTrustedCert();
        this.workingPublicKey = signingCert.getPublicKey();
    }
    List<X500Principal> issuerList = new ArrayList<X500Principal>();
    PKIXExtendedParameters.Builder pkixBuilder;
    try {
        PKIXParameters pkixParams = new PKIXParameters(trustAnchors);
        pkixParams.setRevocationEnabled(false);
        pkixParams.setDate(currentDate);
        for (int i = 0; i != crlCertStores.size(); i++) {
            if (LOG.isLoggable(Level.INFO)) {
                addIssuers(issuerList, crlCertStores.get(i));
            }
            pkixParams.addCertStore(crlCertStores.get(i));
        }
        pkixBuilder = new PKIXExtendedParameters.Builder(pkixParams);
        pkixBuilder.setValidityModel(validityModel);
    } catch (GeneralSecurityException e) {
        throw new RuntimeException("error setting up baseParams: " + e.getMessage());
    }
    for (int i = 0; i != crls.size(); i++) {
        if (LOG.isLoggable(Level.INFO)) {
            addIssuers(issuerList, crls.get(i));
        }
        pkixBuilder.addCRLStore(new LocalCRLStore(crls.get(i)));
    }
    if (issuerList.isEmpty()) {
        LOG.log(Level.INFO, "configured with 0 pre-loaded CRLs");
    } else {
        if (LOG.isLoggable(Level.FINE)) {
            for (int i = 0; i != issuerList.size(); i++) {
                LOG.log(Level.FINE, "configuring with CRL for issuer \"" + issuerList.get(i) + "\"");
            }
        } else {
            LOG.log(Level.INFO, "configured with " + issuerList.size() + " pre-loaded CRLs");
        }
    }
    PKIXExtendedParameters pkixParams = pkixBuilder.build();
    Date validityDate = RevocationUtilities.getValidityDate(pkixParams, currentDate);
    try {
        checkCRLs(pkixParams, currentDate, validityDate, cert, signingCert, workingPublicKey, new ArrayList(), helper);
    } catch (AnnotatedException e) {
        throw new CertPathValidatorException(e.getMessage(), e.getCause());
    } catch (CRLNotFoundException e) {
        if (null == cert.getExtensionValue(Extension.cRLDistributionPoints.getId())) {
            throw e;
        }
        CRL crl;
        try {
            crl = downloadCRLs(cert.getIssuerX500Principal(), currentDate, RevocationUtilities.getExtensionValue(cert, Extension.cRLDistributionPoints), helper);
        } catch (AnnotatedException e1) {
            throw new CertPathValidatorException(e1.getMessage(), e1.getCause());
        }
        if (crl != null) {
            try {
                pkixBuilder.addCRLStore(new LocalCRLStore(new CollectionStore<CRL>(Collections.singleton(crl))));
                pkixParams = pkixBuilder.build();
                validityDate = RevocationUtilities.getValidityDate(pkixParams, currentDate);
                checkCRLs(pkixParams, currentDate, validityDate, cert, signingCert, workingPublicKey, new ArrayList(), helper);
            } catch (AnnotatedException e1) {
                throw new CertPathValidatorException(e1.getMessage(), e1.getCause());
            }
        } else {
            if (!canSoftFail) {
                throw e;
            }
            X500Principal issuer = cert.getIssuerX500Principal();
            Long initial = failures.get(issuer);
            if (initial != null) {
                long period = System.currentTimeMillis() - initial.longValue();
                if (failHardMaxTime != -1 && failHardMaxTime < period) {
                    throw e;
                }
                if (period < failLogMaxTime) {
                    LOG.log(Level.WARNING, "soft failing for issuer: \"" + issuer + "\"");
                } else {
                    LOG.log(Level.SEVERE, "soft failing for issuer: \"" + issuer + "\"");
                }
            } else {
                failures.put(issuer, System.currentTimeMillis());
            }
        }
    }
    this.signingCert = cert;
    this.workingPublicKey = cert.getPublicKey();
    this.workingIssuerName = cert.getSubjectX500Principal();
}
Also used : GeneralSecurityException(java.security.GeneralSecurityException) ArrayList(java.util.ArrayList) TrustAnchor(java.security.cert.TrustAnchor) X509Certificate(java.security.cert.X509Certificate) CRLDistPoint(com.github.zhenwei.core.asn1.x509.CRLDistPoint) DistributionPoint(com.github.zhenwei.core.asn1.x509.DistributionPoint) Date(java.util.Date) CertPathValidatorException(java.security.cert.CertPathValidatorException) PKIXExtendedParameters(com.github.zhenwei.provider.jcajce.PKIXExtendedParameters) PKIXParameters(java.security.cert.PKIXParameters) Iterator(java.util.Iterator) X500Principal(javax.security.auth.x500.X500Principal) X509CRL(java.security.cert.X509CRL) CRL(java.security.cert.CRL)

Example 10 with PKIXExtendedParameters

use of com.github.zhenwei.provider.jcajce.PKIXExtendedParameters in project LinLong-Java by zhenwei1108.

the class X509RevocationChecker method checkCRLs.

/**
 * Checks a certificate if it is revoked.
 *
 * @param pkixParams       PKIX parameters.
 * @param cert             Certificate to check if it is revoked.
 * @param validDate        The date when the certificate revocation status should be checked.
 * @param sign             The issuer certificate of the certificate <code>cert</code>.
 * @param workingPublicKey The public key of the issuer certificate <code>sign</code>.
 * @param certPathCerts    The certificates of the certification path.
 * @throws AnnotatedException if the certificate is revoked or the status cannot be checked or
 *                            some error occurs.
 */
protected void checkCRLs(PKIXExtendedParameters pkixParams, Date currentDate, Date validityDate, X509Certificate cert, X509Certificate sign, PublicKey workingPublicKey, List certPathCerts, JcaJceHelper helper) throws AnnotatedException, CertPathValidatorException {
    CRLDistPoint crldp;
    try {
        crldp = CRLDistPoint.getInstance(RevocationUtilities.getExtensionValue(cert, Extension.cRLDistributionPoints));
    } catch (Exception e) {
        throw new AnnotatedException("cannot read CRL distribution point extension", e);
    }
    CertStatus certStatus = new CertStatus();
    ReasonsMask reasonsMask = new ReasonsMask();
    AnnotatedException lastException = null;
    boolean validCrlFound = false;
    // for each distribution point
    if (crldp != null) {
        DistributionPoint[] dps;
        try {
            dps = crldp.getDistributionPoints();
        } catch (Exception e) {
            throw new AnnotatedException("cannot read distribution points", e);
        }
        if (dps != null) {
            PKIXExtendedParameters.Builder pkixBuilder = new PKIXExtendedParameters.Builder(pkixParams);
            try {
                List extras = getAdditionalStoresFromCRLDistributionPoint(crldp, pkixParams.getNamedCRLStoreMap());
                for (Iterator it = extras.iterator(); it.hasNext(); ) {
                    pkixBuilder.addCRLStore((PKIXCRLStore) it.next());
                }
            } catch (AnnotatedException e) {
                throw new AnnotatedException("no additional CRL locations could be decoded from CRL distribution point extension", e);
            }
            PKIXExtendedParameters pkixParamsFinal = pkixBuilder.build();
            Date validityDateFinal = RevocationUtilities.getValidityDate(pkixParamsFinal, currentDate);
            for (int i = 0; i < dps.length && certStatus.getCertStatus() == CertStatus.UNREVOKED && !reasonsMask.isAllReasons(); i++) {
                try {
                    RFC3280CertPathUtilities.checkCRL(dps[i], pkixParamsFinal, currentDate, validityDateFinal, cert, sign, workingPublicKey, certStatus, reasonsMask, certPathCerts, helper);
                    validCrlFound = true;
                } catch (AnnotatedException e) {
                    lastException = 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.
         */
            X500Principal issuer = cert.getIssuerX500Principal();
            DistributionPoint dp = new DistributionPoint(new DistributionPointName(0, new GeneralNames(new GeneralName(GeneralName.directoryName, X500Name.getInstance(issuer.getEncoded())))), null, null);
            PKIXExtendedParameters pkixParamsClone = (PKIXExtendedParameters) pkixParams.clone();
            RFC3280CertPathUtilities.checkCRL(dp, pkixParamsClone, currentDate, validityDate, cert, sign, workingPublicKey, certStatus, reasonsMask, certPathCerts, helper);
            validCrlFound = true;
        } catch (AnnotatedException e) {
            lastException = e;
        }
    }
    if (!validCrlFound) {
        if (lastException instanceof AnnotatedException) {
            throw new CRLNotFoundException("no valid CRL found", lastException);
        }
        throw new CRLNotFoundException("no valid CRL found");
    }
    if (certStatus.getCertStatus() != CertStatus.UNREVOKED) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");
        df.setTimeZone(TimeZone.getTimeZone("UTC"));
        String message = "certificate [issuer=\"" + cert.getIssuerX500Principal() + "\",serialNumber=" + cert.getSerialNumber() + ",subject=\"" + cert.getSubjectX500Principal() + "\"] revoked after " + df.format(certStatus.getRevocationDate());
        message += ", reason: " + crlReasons[certStatus.getCertStatus()];
        throw new AnnotatedException(message);
    }
    if (!reasonsMask.isAllReasons() && certStatus.getCertStatus() == CertStatus.UNREVOKED) {
        certStatus.setCertStatus(CertStatus.UNDETERMINED);
    }
    if (certStatus.getCertStatus() == CertStatus.UNDETERMINED) {
        throw new AnnotatedException("certificate status could not be determined");
    }
}
Also used : DistributionPointName(com.github.zhenwei.core.asn1.x509.DistributionPointName) KeyStoreException(java.security.KeyStoreException) GeneralSecurityException(java.security.GeneralSecurityException) CertPathValidatorException(java.security.cert.CertPathValidatorException) CertStoreException(java.security.cert.CertStoreException) Date(java.util.Date) CRLDistPoint(com.github.zhenwei.core.asn1.x509.CRLDistPoint) DistributionPoint(com.github.zhenwei.core.asn1.x509.DistributionPoint) PKIXExtendedParameters(com.github.zhenwei.provider.jcajce.PKIXExtendedParameters) GeneralNames(com.github.zhenwei.core.asn1.x509.GeneralNames) Iterator(java.util.Iterator) X500Principal(javax.security.auth.x500.X500Principal) List(java.util.List) ArrayList(java.util.ArrayList) DistributionPoint(com.github.zhenwei.core.asn1.x509.DistributionPoint) GeneralName(com.github.zhenwei.core.asn1.x509.GeneralName) CRLDistPoint(com.github.zhenwei.core.asn1.x509.CRLDistPoint) SimpleDateFormat(java.text.SimpleDateFormat)

Aggregations

PKIXExtendedParameters (com.github.zhenwei.provider.jcajce.PKIXExtendedParameters)13 Iterator (java.util.Iterator)11 ArrayList (java.util.ArrayList)10 CertPathValidatorException (java.security.cert.CertPathValidatorException)9 X509Certificate (java.security.cert.X509Certificate)9 List (java.util.List)9 CertPathBuilderException (java.security.cert.CertPathBuilderException)8 CRLDistPoint (com.github.zhenwei.core.asn1.x509.CRLDistPoint)7 DistributionPoint (com.github.zhenwei.core.asn1.x509.DistributionPoint)7 IOException (java.io.IOException)7 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)7 PKIXExtendedBuilderParameters (com.github.zhenwei.provider.jcajce.PKIXExtendedBuilderParameters)6 ExtCertPathValidatorException (com.github.zhenwei.provider.jce.exception.ExtCertPathValidatorException)6 HashSet (java.util.HashSet)6 LinkedHashSet (java.util.LinkedHashSet)6 PKIXCertStoreSelector (com.github.zhenwei.provider.jcajce.PKIXCertStoreSelector)5 Date (java.util.Date)5 Set (java.util.Set)5 X500Name (com.github.zhenwei.core.asn1.x500.X500Name)4 ExtendedPKIXParameters (com.github.zhenwei.provider.x509.ExtendedPKIXParameters)4