Example usage for java.security.cert X509CRL getThisUpdate

List of usage examples for java.security.cert X509CRL getThisUpdate

Introduction

In this page you can find the example usage for java.security.cert X509CRL getThisUpdate.

Prototype

public abstract Date getThisUpdate();

Source Link

Document

Gets the thisUpdate date from the CRL.

Usage

From source file:com.netscape.cms.publish.publishers.FileBasedPublisher.java

private String[] getCrlNamePrefix(X509CRL crl, boolean useGMT) {
    String[] namePrefix = { getGeneralCrlPrefix(), getGeneralCrlPrefix() };

    java.text.SimpleDateFormat format = new java.text.SimpleDateFormat("yyyyMMdd-HHmmss");
    TimeZone tz = TimeZone.getTimeZone("GMT");
    if (useGMT)/*  ww w.  ja va  2s  . c  o  m*/
        format.setTimeZone(tz);
    String timeStamp = format.format(crl.getThisUpdate()).toString();
    namePrefix[0] += "-" + timeStamp;
    if (((netscape.security.x509.X509CRLImpl) crl).isDeltaCRL()) {
        namePrefix[0] += "-delta";
        namePrefix[1] += "-delta";
    }

    return namePrefix;
}

From source file:eu.europa.ec.markt.dss.signature.xades.XAdESProfileC.java

private void incorporateCRLRefs(CompleteRevocationRefsType completeRevocationRefs, ValidationContext ctx) {
    if (!ctx.getNeededCRL().isEmpty()) {
        CRLRefsType crlRefs = xadesObjectFactory.createCRLRefsType();
        completeRevocationRefs.setCRLRefs(crlRefs);
        List<CRLRefType> crlRefList = crlRefs.getCRLRef();

        for (X509CRL crl : ctx.getNeededCRL()) {
            try {
                CRLRefType crlRef = xadesObjectFactory.createCRLRefType();

                CRLIdentifierType crlIdentifier = xadesObjectFactory.createCRLIdentifierType();
                crlRef.setCRLIdentifier(crlIdentifier);
                String issuerName = crl.getIssuerX500Principal().getName();
                crlIdentifier.setIssuer(issuerName);

                GregorianCalendar cal = (GregorianCalendar) GregorianCalendar.getInstance();
                cal.setTime(crl.getThisUpdate());
                crlIdentifier.setIssueTime(this.datatypeFactory.newXMLGregorianCalendar(cal));

                // crlIdentifier.setNumber(getCrlNumber(encodedCrl));

                DigestAlgAndValueType digestAlgAndValue = getDigestAlgAndValue(crl.getEncoded(),
                        DigestAlgorithm.SHA1);
                crlRef.setDigestAlgAndValue(digestAlgAndValue);

                crlRefList.add(crlRef);//from   w w w .j a v a 2 s  .  co  m
            } catch (CRLException ex) {
                throw new RuntimeException(ex);
            }
        }
    }
}

From source file:be.fedict.trust.crl.CachedCrlRepository.java

public X509CRL findCrl(URI crlUri, X509Certificate issuerCertificate, Date validationDate) {

    SoftReference<X509CRL> crlRef = this.crlCache.get(crlUri);
    if (null == crlRef) {
        LOG.debug("no CRL entry found: " + crlUri);
        return refreshCrl(crlUri, issuerCertificate, validationDate);
    }/*from  w  w  w .ja va2s .c  om*/
    X509CRL crl = crlRef.get();
    if (null == crl) {
        LOG.debug("CRL garbage collected: " + crlUri);
        return refreshCrl(crlUri, issuerCertificate, validationDate);
    }
    if (validationDate.after(crl.getNextUpdate())) {
        LOG.debug("CRL no longer valid: " + crlUri);
        LOG.debug("validation date: " + validationDate);
        LOG.debug("CRL next update: " + crl.getNextUpdate());
        return refreshCrl(crlUri, issuerCertificate, validationDate);
    }
    /*
     * The Belgian PKI the nextUpdate CRL extension indicates 7 days. The
     * actual CRL refresh rate is every 3 hours. So it's a bit dangerous to
     * only base the CRL cache refresh strategy on the nextUpdate field as
     * indicated by the CRL.
     */
    Date thisUpdate = crl.getThisUpdate();
    DateTime cacheMaturityDateTime = new DateTime(thisUpdate).plusHours(this.cacheAgingHours);
    if (validationDate.after(cacheMaturityDateTime.toDate())) {
        LOG.debug("refreshing the CRL cache: " + crlUri);
        return refreshCrl(crlUri, issuerCertificate, validationDate);
    }
    LOG.debug("using cached CRL: " + crlUri);
    return crl;
}

From source file:eu.europa.esig.dss.xades.signature.XAdESLevelC.java

private void incorporateCRLRefs(Element completeRevocationRefsDom,
        final Set<RevocationToken> processedRevocationTokens) throws DSSException {

    if (processedRevocationTokens.isEmpty()) {

        return;/* www  .  j a  v a2s .  c om*/
    }

    boolean containsCrlToken = false;
    for (RevocationToken revocationToken : processedRevocationTokens) {
        containsCrlToken = revocationToken instanceof CRLToken;
        if (containsCrlToken) {
            break;
        }
    }

    if (!containsCrlToken) {
        return;
    }
    // <xades:CRLRefs>
    // ...<xades:CRLRef>
    // ......<xades:DigestAlgAndValue>
    // .........<ds:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/>
    // .........<ds:DigestValue>G+z+DaZ6X44wEOueVYvZGmTh4dBkjjctKxcJYEV4HmU=</ds:DigestValue>
    // ......</xades:DigestAlgAndValue>
    // ......<xades:CRLIdentifier URI="LevelACAOK.crl">
    // ...<xades:Issuer>CN=LevelACAOK,OU=Plugtests_STF-428_2011-2012,O=ETSI,C=FR</xades:Issuer>
    // ...<xades:IssueTime>2012-03-13T13:58:28.000-03:00</xades:IssueTime>
    // ...<xades:Number>4415260066222</xades:Number>

    final Element crlRefsDom = DSSXMLUtils.addElement(documentDom, completeRevocationRefsDom,
            XAdESNamespaces.XAdES, "xades:CRLRefs");

    for (final RevocationToken revocationToken : processedRevocationTokens) {

        if (revocationToken instanceof CRLToken) {

            final X509CRL crl = ((CRLToken) revocationToken).getX509crl();

            final Element crlRefDom = DSSXMLUtils.addElement(documentDom, crlRefsDom, XAdESNamespaces.XAdES,
                    "xades:CRLRef");

            final Element digestAlgAndValueDom = DSSXMLUtils.addElement(documentDom, crlRefDom,
                    XAdESNamespaces.XAdES, "xades:DigestAlgAndValue");
            // TODO: to be added as field to eu.europa.esig.dss.AbstractSignatureParameters.
            DigestAlgorithm digestAlgorithm = DigestAlgorithm.SHA1;
            incorporateDigestMethod(digestAlgAndValueDom, digestAlgorithm);

            final InMemoryDocument inMemoryDocument = new InMemoryDocument(revocationToken.getEncoded());
            incorporateDigestValue(digestAlgAndValueDom, digestAlgorithm, inMemoryDocument);

            final Element crlIdentifierDom = DSSXMLUtils.addElement(documentDom, crlRefDom,
                    XAdESNamespaces.XAdES, "xades:CRLIdentifier");
            // crlIdentifierDom.setAttribute("URI",".crl");
            final String issuerX500PrincipalName = crl.getIssuerX500Principal().getName();
            DSSXMLUtils.addTextElement(documentDom, crlIdentifierDom, XAdESNamespaces.XAdES, "xades:Issuer",
                    issuerX500PrincipalName);

            final Date thisUpdate = crl.getThisUpdate();
            XMLGregorianCalendar xmlGregorianCalendar = DSSXMLUtils.createXMLGregorianCalendar(thisUpdate);
            final String thisUpdateAsXmlFormat = xmlGregorianCalendar.toXMLFormat();
            DSSXMLUtils.addTextElement(documentDom, crlIdentifierDom, XAdESNamespaces.XAdES, "xades:IssueTime",
                    thisUpdateAsXmlFormat);

            // DSSXMLUtils.addTextElement(documentDom, crlRefDom, XAdESNamespaces.XAdES, "xades:Number", ???);
        }
    }
}

From source file:gov.nih.nci.cagrid.gts.service.ProxyPathValidator.java

protected void checkCRL(X509Certificate cert, CertificateRevocationLists crlsList,
        TrustedCertificates trustedCerts) throws ProxyPathValidatorException {
    if (crlsList == null) {
        return;/*from w  w w . j  a v a2s  .c om*/
    }

    logger.debug("checkCRLs: enter");
    // Should not happen, just a sanity check.
    if (trustedCerts == null) {
        String err = "Trusted certificates are null, cannot verify CRLs";
        logger.error(err);
        throw new ProxyPathValidatorException(ProxyPathValidatorException.FAILURE, null, err);
    }

    String issuerName = cert.getIssuerDN().getName();
    X509CRL crl = crlsList.getCrl(issuerName);
    if (crl == null) {
        logger.debug("No CRL for certificate");
        return;
    }

    // get CA cert for the CRL
    X509Certificate x509Cert = trustedCerts.getCertificate(issuerName);
    if (x509Cert == null) {
        // if there is no trusted certs from that CA, then
        // the chain cannot contain a cert from that CA,
        // which implies not checking this CRL should be fine.
        logger.debug("No trusted cert with this CA signature");
        return;
    }

    // validate CRL
    try {
        crl.verify(x509Cert.getPublicKey());
    } catch (Exception exp) {
        logger.error("CRL verification failed");
        throw new ProxyPathValidatorException(ProxyPathValidatorException.FAILURE, exp);
    }

    Date now = new Date();
    // check date validity of CRL
    if ((crl.getThisUpdate().before(now))
            || ((crl.getNextUpdate() != null) && (crl.getNextUpdate().after(now)))) {
        if (crl.isRevoked(cert)) {
            throw new ProxyPathValidatorException(ProxyPathValidatorException.REVOKED, cert,
                    "This cert " + cert.getSubjectDN().getName() + " is on a CRL");
        }
    }

    logger.debug("checkCRLs: exit");
}

From source file:be.fedict.eid.applet.service.signer.facets.XAdESXLSignatureFacet.java

public void postSign(Element signatureElement, List<X509Certificate> signingCertificateChain) {
    LOG.debug("XAdES-X-L post sign phase");
    for (X509Certificate xCert : signingCertificateChain) {
        LOG.debug("Cert chain: " + xCert.getSubjectX500Principal());
    }//w w  w . java2  s .c  om

    // check for XAdES-BES
    Element qualifyingPropertiesElement = (Element) findSingleNode(signatureElement,
            "ds:Object/xades:QualifyingProperties");
    if (null == qualifyingPropertiesElement) {
        throw new IllegalArgumentException("no XAdES-BES extension present");
    }

    // create basic XML container structure
    Document document = signatureElement.getOwnerDocument();
    String xadesNamespacePrefix;
    if (null != qualifyingPropertiesElement.getPrefix()) {
        xadesNamespacePrefix = qualifyingPropertiesElement.getPrefix() + ":";
    } else {
        xadesNamespacePrefix = "";
    }
    Element unsignedPropertiesElement = (Element) findSingleNode(qualifyingPropertiesElement,
            "xades:UnsignedProperties");
    if (null == unsignedPropertiesElement) {
        unsignedPropertiesElement = document.createElementNS(XADES_NAMESPACE,
                xadesNamespacePrefix + "UnsignedProperties");
        qualifyingPropertiesElement.appendChild(unsignedPropertiesElement);
    }
    Element unsignedSignaturePropertiesElement = (Element) findSingleNode(unsignedPropertiesElement,
            "xades:UnsignedSignatureProperties");
    if (null == unsignedSignaturePropertiesElement) {
        unsignedSignaturePropertiesElement = document.createElementNS(XADES_NAMESPACE,
                xadesNamespacePrefix + "UnsignedSignatureProperties");
        unsignedPropertiesElement.appendChild(unsignedSignaturePropertiesElement);
    }

    // create the XAdES-T time-stamp
    Node signatureValueNode = findSingleNode(signatureElement, "ds:SignatureValue");
    RevocationData tsaRevocationDataXadesT = new RevocationData();
    LOG.debug("creating XAdES-T time-stamp");
    XAdESTimeStampType signatureTimeStamp = createXAdESTimeStamp(Collections.singletonList(signatureValueNode),
            tsaRevocationDataXadesT, this.c14nAlgoId, this.timeStampService, this.objectFactory,
            this.xmldsigObjectFactory);

    // marshal the XAdES-T extension
    try {
        this.marshaller.marshal(this.objectFactory.createSignatureTimeStamp(signatureTimeStamp),
                unsignedSignaturePropertiesElement);
    } catch (JAXBException e) {
        throw new RuntimeException("JAXB error: " + e.getMessage(), e);
    }

    // xadesv141::TimeStampValidationData
    if (tsaRevocationDataXadesT.hasRevocationDataEntries()) {
        ValidationDataType validationData = createValidationData(tsaRevocationDataXadesT);
        try {
            this.marshaller.marshal(this.xades141ObjectFactory.createTimeStampValidationData(validationData),
                    unsignedSignaturePropertiesElement);
        } catch (JAXBException e) {
            throw new RuntimeException("JAXB error: " + e.getMessage(), e);
        }
    }

    if (null == this.revocationDataService) {
        /*
         * Without revocation data service we cannot construct the XAdES-C
         * extension.
         */
        return;
    }

    // XAdES-C: complete certificate refs
    CompleteCertificateRefsType completeCertificateRefs = this.objectFactory
            .createCompleteCertificateRefsType();
    CertIDListType certIdList = this.objectFactory.createCertIDListType();
    completeCertificateRefs.setCertRefs(certIdList);
    List<CertIDType> certIds = certIdList.getCert();
    for (int certIdx = 1; certIdx < signingCertificateChain.size(); certIdx++) {
        /*
         * We skip the signing certificate itself according to section
         * 4.4.3.2 of the XAdES 1.4.1 specification.
         */
        X509Certificate certificate = signingCertificateChain.get(certIdx);
        CertIDType certId = XAdESSignatureFacet.getCertID(certificate, this.objectFactory,
                this.xmldsigObjectFactory, this.digestAlgorithm, false);
        certIds.add(certId);
    }

    // XAdES-C: complete revocation refs
    CompleteRevocationRefsType completeRevocationRefs = this.objectFactory.createCompleteRevocationRefsType();
    RevocationData revocationData = this.revocationDataService.getRevocationData(signingCertificateChain);
    if (revocationData.hasCRLs()) {
        CRLRefsType crlRefs = this.objectFactory.createCRLRefsType();
        completeRevocationRefs.setCRLRefs(crlRefs);
        List<CRLRefType> crlRefList = crlRefs.getCRLRef();

        List<byte[]> crls = revocationData.getCRLs();
        for (byte[] encodedCrl : crls) {
            CRLRefType crlRef = this.objectFactory.createCRLRefType();
            crlRefList.add(crlRef);
            X509CRL crl;
            try {
                crl = (X509CRL) this.certificateFactory.generateCRL(new ByteArrayInputStream(encodedCrl));
            } catch (CRLException e) {
                throw new RuntimeException("CRL parse error: " + e.getMessage(), e);
            }

            CRLIdentifierType crlIdentifier = this.objectFactory.createCRLIdentifierType();
            crlRef.setCRLIdentifier(crlIdentifier);
            String issuerName;
            try {
                issuerName = PrincipalUtil.getIssuerX509Principal(crl).getName().replace(",", ", ");
            } catch (CRLException e) {
                throw new RuntimeException("CRL encoding error: " + e.getMessage(), e);
            }
            crlIdentifier.setIssuer(issuerName);
            crlIdentifier.setIssueTime(this.datatypeFactory
                    .newXMLGregorianCalendar(new DateTime(crl.getThisUpdate()).toGregorianCalendar()));
            crlIdentifier.setNumber(getCrlNumber(crl));

            DigestAlgAndValueType digestAlgAndValue = XAdESSignatureFacet.getDigestAlgAndValue(encodedCrl,
                    this.objectFactory, this.xmldsigObjectFactory, this.digestAlgorithm);
            crlRef.setDigestAlgAndValue(digestAlgAndValue);
        }
    }
    if (revocationData.hasOCSPs()) {
        OCSPRefsType ocspRefs = this.objectFactory.createOCSPRefsType();
        completeRevocationRefs.setOCSPRefs(ocspRefs);
        List<OCSPRefType> ocspRefList = ocspRefs.getOCSPRef();
        List<byte[]> ocsps = revocationData.getOCSPs();
        for (byte[] ocsp : ocsps) {
            OCSPRefType ocspRef = this.objectFactory.createOCSPRefType();
            ocspRefList.add(ocspRef);

            DigestAlgAndValueType digestAlgAndValue = XAdESSignatureFacet.getDigestAlgAndValue(ocsp,
                    this.objectFactory, this.xmldsigObjectFactory, this.digestAlgorithm);
            ocspRef.setDigestAlgAndValue(digestAlgAndValue);

            OCSPIdentifierType ocspIdentifier = this.objectFactory.createOCSPIdentifierType();
            ocspRef.setOCSPIdentifier(ocspIdentifier);
            OCSPResp ocspResp;
            try {
                ocspResp = new OCSPResp(ocsp);
            } catch (IOException e) {
                throw new RuntimeException("OCSP decoding error: " + e.getMessage(), e);
            }
            Object ocspResponseObject;
            try {
                ocspResponseObject = ocspResp.getResponseObject();
            } catch (OCSPException e) {
                throw new RuntimeException("OCSP error: " + e.getMessage(), e);
            }
            BasicOCSPResp basicOcspResp = (BasicOCSPResp) ocspResponseObject;
            Date producedAt = basicOcspResp.getProducedAt();
            ocspIdentifier.setProducedAt(this.datatypeFactory
                    .newXMLGregorianCalendar(new DateTime(producedAt).toGregorianCalendar()));

            ResponderIDType responderId = this.objectFactory.createResponderIDType();
            ocspIdentifier.setResponderID(responderId);
            RespID respId = basicOcspResp.getResponderId();
            ResponderID ocspResponderId = respId.toASN1Object();
            DERTaggedObject derTaggedObject = (DERTaggedObject) ocspResponderId.toASN1Object();
            if (2 == derTaggedObject.getTagNo()) {
                ASN1OctetString keyHashOctetString = (ASN1OctetString) derTaggedObject.getObject();
                responderId.setByKey(keyHashOctetString.getOctets());
            } else {
                X509Name name = X509Name.getInstance(derTaggedObject.getObject());
                responderId.setByName(name.toString());
            }
        }
    }

    // marshal XAdES-C
    NodeList unsignedSignaturePropertiesNodeList = ((Element) qualifyingPropertiesElement)
            .getElementsByTagNameNS(XADES_NAMESPACE, "UnsignedSignatureProperties");
    Node unsignedSignaturePropertiesNode = unsignedSignaturePropertiesNodeList.item(0);
    try {
        this.marshaller.marshal(this.objectFactory.createCompleteCertificateRefs(completeCertificateRefs),
                unsignedSignaturePropertiesNode);
        this.marshaller.marshal(this.objectFactory.createCompleteRevocationRefs(completeRevocationRefs),
                unsignedSignaturePropertiesNode);
    } catch (JAXBException e) {
        throw new RuntimeException("JAXB error: " + e.getMessage(), e);
    }

    // XAdES-X Type 1 timestamp
    List<Node> timeStampNodesXadesX1 = new LinkedList<Node>();
    timeStampNodesXadesX1.add(signatureValueNode);
    Node signatureTimeStampNode = findSingleNode(unsignedSignaturePropertiesNode, "xades:SignatureTimeStamp");
    timeStampNodesXadesX1.add(signatureTimeStampNode);
    Node completeCertificateRefsNode = findSingleNode(unsignedSignaturePropertiesNode,
            "xades:CompleteCertificateRefs");
    timeStampNodesXadesX1.add(completeCertificateRefsNode);
    Node completeRevocationRefsNode = findSingleNode(unsignedSignaturePropertiesNode,
            "xades:CompleteRevocationRefs");
    timeStampNodesXadesX1.add(completeRevocationRefsNode);

    RevocationData tsaRevocationDataXadesX1 = new RevocationData();
    LOG.debug("creating XAdES-X time-stamp");
    XAdESTimeStampType timeStampXadesX1 = createXAdESTimeStamp(timeStampNodesXadesX1, tsaRevocationDataXadesX1,
            this.c14nAlgoId, this.timeStampService, this.objectFactory, this.xmldsigObjectFactory);
    ValidationDataType timeStampXadesX1ValidationData;
    if (tsaRevocationDataXadesX1.hasRevocationDataEntries()) {
        timeStampXadesX1ValidationData = createValidationData(tsaRevocationDataXadesX1);
    } else {
        timeStampXadesX1ValidationData = null;
    }

    // marshal XAdES-X
    try {
        this.marshaller.marshal(this.objectFactory.createSigAndRefsTimeStamp(timeStampXadesX1),
                unsignedSignaturePropertiesNode);
        if (null != timeStampXadesX1ValidationData) {
            this.marshaller.marshal(
                    this.xades141ObjectFactory.createTimeStampValidationData(timeStampXadesX1ValidationData),
                    unsignedSignaturePropertiesNode);
        }
    } catch (JAXBException e) {
        throw new RuntimeException("JAXB error: " + e.getMessage(), e);
    }

    // XAdES-X-L
    CertificateValuesType certificateValues = this.objectFactory.createCertificateValuesType();
    List<Object> certificateValuesList = certificateValues.getEncapsulatedX509CertificateOrOtherCertificate();
    for (X509Certificate certificate : signingCertificateChain) {
        EncapsulatedPKIDataType encapsulatedPKIDataType = this.objectFactory.createEncapsulatedPKIDataType();
        try {
            encapsulatedPKIDataType.setValue(certificate.getEncoded());
        } catch (CertificateEncodingException e) {
            throw new RuntimeException("certificate encoding error: " + e.getMessage(), e);
        }
        certificateValuesList.add(encapsulatedPKIDataType);
    }
    RevocationValuesType revocationValues = createRevocationValues(revocationData);

    // marshal XAdES-X-L
    try {
        this.marshaller.marshal(this.objectFactory.createCertificateValues(certificateValues),
                unsignedSignaturePropertiesNode);
        this.marshaller.marshal(this.objectFactory.createRevocationValues(revocationValues),
                unsignedSignaturePropertiesNode);
    } catch (JAXBException e) {
        throw new RuntimeException("JAXB error: " + e.getMessage(), e);
    }
}

From source file:mitm.common.security.crl.PKIXRevocationChecker.java

private RevocationDetail getRevocationDetail(List<X509CRL> crls, X509Certificate targetCertificate,
        X509Certificate issuerCertificate, PublicKey issuerPublicKey, Date now) throws NoSuchProviderException {
    RevocationDetailImpl detail = new RevocationDetailImpl(RevocationStatus.UNKNOWN);

    boolean validCRLFound = false;

    int reasonMask = 0;

    for (X509CRL crl : crls) {
        BigInteger serialNumber = targetCertificate.getSerialNumber();

        X509CRLEntry crlEntry = crl.getRevokedCertificate(serialNumber);

        Date revocationDate = null;

        if (crlEntry != null) {
            revocationDate = crlEntry.getRevocationDate();

            if (revocationDate == null || !now.before(revocationDate)) {
                /*//from  w  ww.j a v a  2s  .  co m
                 * X.509 7.3 NOTE 4  When an implementation processing a certificate revocation list does not 
                 * recognize a critical extension in the crlEntryExtensions field, it shall assume that, 
                 * at a minimum, the identified certificate has been revoked and is no longer valid and 
                 * perform additional actions concerning that revoked certificate as dictated by local policy.
                 *
                 * We do not need to check for unsupported critical extension because if we do not support them
                 * we should assume that the certificate is revoked.
                 */

                // TODO: add support for onHold/removeFromCRL

                Integer reasonCode = null;
                try {
                    reasonCode = X509CRLEntryInspector.getReasonCode(crlEntry);
                } catch (IOException e) {
                    logger.error("Error retrieving reasonCode.", e);
                }

                detail = (reasonCode != null ? new RevocationDetailImpl(RevocationStatus.REVOKED, reasonCode)
                        : new RevocationDetailImpl(RevocationStatus.REVOKED));

                /* there is no need to continue because certificate is revoked */
                break;
            } else {
                if (now.before(revocationDate)) {
                    logger.info("Certificate is revoked in the future.");
                }
            }
        }

        if (hasUnsupportedCriticalExtensions(crl)) {
            logger.debug("The CRL has unsupported critical extensions.");

            detail = new RevocationDetailImpl(RevocationStatus.UNSUPPORTED_CRITICAL_EXTENSION);

            continue;
        }

        /*
         * check that the start time the CRL is valid is before the time the certificate is 
         * no longer valid. In other words, that the expiration date of the certificate is 
         * later than the date the CRL was issued. It is possible that the certificate was
         * at some point revoked but the CA removed it because the certificate is no longer 
         * valid
         */
        if (crl.getThisUpdate() != null && targetCertificate.getNotAfter().before(crl.getThisUpdate())) {
            logger.info("Certificate has expired before the CRL was valid.");

            continue;
        }

        try {
            if (X509CRLInspector.isDeltaCRL(crl)) {
                DeltaCRLStatus deltaStatus = getDeltaCRLStatus(targetCertificate, crl, issuerPublicKey, now);

                if (deltaStatus == DeltaCRLStatus.UNSUPPORTED_CRITICAL_EXTENSION) {
                    detail = new RevocationDetailImpl(RevocationStatus.UNSUPPORTED_CRITICAL_EXTENSION);

                    continue;
                } else if (deltaStatus == DeltaCRLStatus.UNKNOWN) {
                    continue;
                }
            } else {
                if (!acceptCRL_6_3_3_b(targetCertificate, crl)) {
                    logger.debug("CRL not valid according to acceptCRL_6_3_3_b.");
                    continue;
                }
            }
        } catch (IOException e) {
            logger.error("Error inspecting CRL.", e);

            continue;
        }

        if (crl.getNextUpdate() != null && now.after(crl.getNextUpdate())) {
            /*
             * an CRL cannot really expire but, when we want at least to log that the 
             * nextUpdate is overdue
             */
            logger.debug("The CRL next update is overdue.");

            /* we need to set the nextUpdate if this is a newer CRL */

            if (detail.getStatus() != RevocationStatus.EXPIRED || detail.getNextUpdate() == null) {
                detail = new RevocationDetailImpl(RevocationStatus.EXPIRED, crl.getNextUpdate());
            } else {
                if (crl.getNextUpdate().after(detail.getNextUpdate())) {
                    /* the nextUpdate of the current CRL is later so it's longer valid */
                    detail = new RevocationDetailImpl(RevocationStatus.EXPIRED, crl.getNextUpdate());
                }
            }

            continue;
        }

        try {
            reasonMask = reasonMask | getInterimReasonsMask(targetCertificate, crl);

            /* a valid crl was found. Continue search. */
            validCRLFound = true;
        } catch (IOException e) {
            logger.error("Error getting interim mask.", e);
        }
    }

    /*
     * if one the CRLs was good and the certificate was not revoked we will set the 
     * status to NOT_REVOKED
     */
    if (validCRLFound && detail.getStatus() != RevocationStatus.REVOKED) {
        /* check if all reasons are covered */
        if (reasonMask == allReasons) {
            detail = new RevocationDetailImpl(RevocationStatus.NOT_REVOKED);
        } else {
            logger.debug("Not all reasons were covered.");

            detail = new RevocationDetailImpl(RevocationStatus.UNKNOWN);
        }
    }

    return detail;
}

From source file:be.fedict.trust.service.bean.HarvesterMDB.java

private void processHarvestMessage(HarvestMessage harvestMessage) {
    if (null == harvestMessage) {
        return;/*  www .  j  a  v  a 2s.c  o m*/
    }
    String caName = harvestMessage.getCaName();
    boolean update = harvestMessage.isUpdate();
    String crlFilePath = harvestMessage.getCrlFile();
    File crlFile = new File(crlFilePath);

    LOG.debug("processHarvestMessage - Don't have CA's Serial Number??");
    LOG.debug("issuer: " + caName);
    CertificateAuthorityEntity certificateAuthority = this.certificateAuthorityDAO
            .findCertificateAuthority(caName);
    if (null == certificateAuthority) {
        LOG.error("unknown certificate authority: " + caName);
        deleteCrlFile(crlFile);
        return;
    }
    if (!update && Status.PROCESSING != certificateAuthority.getStatus()) {
        /*
         * Possible that another harvester instance already activated or is
         * processing the CA cache in the meanwhile.
         */
        LOG.debug("CA status not marked for processing");
        deleteCrlFile(crlFile);
        return;
    }

    Date validationDate = new Date();

    X509Certificate issuerCertificate = certificateAuthority.getCertificate();

    Date notAfter = issuerCertificate.getNotAfter();
    if (validationDate.after(notAfter)) {
        LOG.info("will not update CRL cache for expired CA: " + issuerCertificate.getSubjectX500Principal());
        deleteCrlFile(crlFile);
        return;
    }

    FileInputStream crlInputStream;
    try {
        crlInputStream = new FileInputStream(crlFile);
    } catch (FileNotFoundException e) {
        LOG.error("CRL file does not exist: " + crlFilePath);
        return;
    }
    X509CRL crl;
    try {
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC");
        crl = (X509CRL) certificateFactory.generateCRL(crlInputStream);
    } catch (Exception e) {
        LOG.error("BC error: " + e.getMessage(), e);
        deleteCrlFile(crlFile);
        return;
    }

    LOG.debug("checking integrity CRL...");
    boolean crlValid = CrlTrustLinker.checkCrlIntegrity(crl, issuerCertificate, validationDate);
    if (!crlValid) {
        this.auditDAO.logAudit("Invalid CRL for CA=" + caName);
        deleteCrlFile(crlFile);
        return;
    }
    BigInteger crlNumber = getCrlNumber(crl);
    LOG.debug("CRL number: " + crlNumber);

    BigInteger currentCrlNumber = this.certificateAuthorityDAO.findCrlNumber(caName);
    if (null != currentCrlNumber) {
        LOG.debug("CRL number in database: " + currentCrlNumber);
    }
    if (null != currentCrlNumber && currentCrlNumber.compareTo(crlNumber) >= 0
            && certificateAuthority.getStatus() == Status.ACTIVE) {
        // current CRL cache is higher or equal, no update needed
        LOG.debug("current CA cache is new enough.");
        deleteCrlFile(crlFile);
        return;
    }

    List<RevokedCertificateEntity> revokedCertificateEntities = this.certificateAuthorityDAO
            .getRevokedCertificates(caName);
    LOG.debug("number of revoked certificates in database: " + revokedCertificateEntities.size());
    Map<String, RevokedCertificateEntity> revokedCertificatesMap = new HashMap<String, RevokedCertificateEntity>();
    for (RevokedCertificateEntity revokedCertificateEntity : revokedCertificateEntities) {
        String serialNumber = revokedCertificateEntity.getPk().getSerialNumber();
        revokedCertificatesMap.put(serialNumber, revokedCertificateEntity);
    }

    LOG.debug("processing CRL... " + caName);
    boolean isIndirect;
    Enumeration revokedCertificatesEnum;
    try {
        isIndirect = isIndirectCRL(crl);
        revokedCertificatesEnum = getRevokedCertificatesEnum(crl);
    } catch (Exception e) {
        this.auditDAO.logAudit("Failed to parse CRL for CA=" + caName);
        this.failures++;
        throw new RuntimeException(e);
    }

    int entries = 0;
    if (revokedCertificatesEnum.hasMoreElements()) {
        /*
         * Split up persisting the crl entries to avoid memory issues.
         */
        Set<X509CRLEntry> revokedCertsBatch = new HashSet<X509CRLEntry>();
        X500Principal previousCertificateIssuer = crl.getIssuerX500Principal();
        int added = 0;
        while (revokedCertificatesEnum.hasMoreElements()) {

            TBSCertList.CRLEntry entry = (TBSCertList.CRLEntry) revokedCertificatesEnum.nextElement();
            X500Name x500name = new X500Name(previousCertificateIssuer.getName(X500Principal.RFC1779));
            X509CRLEntryObject revokedCertificate = new X509CRLEntryObject(entry, isIndirect, x500name);
            previousCertificateIssuer = revokedCertificate.getCertificateIssuer();

            revokedCertsBatch.add(revokedCertificate);
            added++;
            if (added == BATCH_SIZE) {
                /*
                 * Persist batch
                 */
                this.certificateAuthorityDAO.updateRevokedCertificates(revokedCertsBatch, crlNumber,
                        crl.getIssuerX500Principal(), revokedCertificatesMap);
                entries += revokedCertsBatch.size();
                revokedCertsBatch.clear();
                added = 0;
            }
        }
        /*
         * Persist final batch
         */
        this.certificateAuthorityDAO.updateRevokedCertificates(revokedCertsBatch, crlNumber,
                crl.getIssuerX500Principal(), revokedCertificatesMap);
        entries += revokedCertsBatch.size();

        /*
         * Cleanup redundant CRL entries
         */
        if (null != crlNumber) {
            this.certificateAuthorityDAO.removeOldRevokedCertificates(crlNumber,
                    crl.getIssuerX500Principal().toString());
        }
    }

    deleteCrlFile(crlFile);

    LOG.debug("CRL this update: " + crl.getThisUpdate());
    LOG.debug("CRL next update: " + crl.getNextUpdate());
    certificateAuthority.setStatus(Status.ACTIVE);
    certificateAuthority.setThisUpdate(crl.getThisUpdate());
    certificateAuthority.setNextUpdate(crl.getNextUpdate());
    LOG.debug("cache activated for CA: " + crl.getIssuerX500Principal() + " (entries=" + entries + ")");
}

From source file:org.candlepin.util.X509CRLStreamWriterTest.java

@Test
public void testAddEntryToEmptyCRL() throws Exception {
    Date oneHourAgo = new Date(new Date().getTime() - 60L * 60L * 1000L);
    Date oneHourHence = new Date(new Date().getTime() + 60L * 60L * 1000L);

    X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(issuer, oneHourAgo);
    crlBuilder.addExtension(X509Extension.authorityKeyIdentifier, false,
            new AuthorityKeyIdentifierStructure(keyPair.getPublic()));
    /* With a CRL number of 127, incrementing it should cause the number of bytes in the length
     * portion of the TLV to increase by one.*/
    crlBuilder.addExtension(X509Extension.cRLNumber, false, new CRLNumber(new BigInteger("127")));
    crlBuilder.setNextUpdate(oneHourHence);
    X509CRLHolder holder = crlBuilder.build(signer);

    File crlToChange = writeCRL(holder);

    File outfile = new File(folder.getRoot(), "new.crl");
    X509CRLStreamWriter stream = new X509CRLStreamWriter(crlToChange, (RSAPrivateKey) keyPair.getPrivate(),
            (RSAPublicKey) keyPair.getPublic());

    // Add enough items to cause the number of length bytes to change
    Set<BigInteger> newSerials = new HashSet<BigInteger>(Arrays.asList(new BigInteger("2358215310"),
            new BigInteger("7231352433"), new BigInteger("8233181205"), new BigInteger("1455615868"),
            new BigInteger("4323487764"), new BigInteger("6673256679")));

    for (BigInteger i : newSerials) {
        stream.add(i, new Date(), CRLReason.privilegeWithdrawn);
    }//ww w.j  a v  a2 s . c  om

    stream.preScan(crlToChange).lock();
    OutputStream o = new BufferedOutputStream(new FileOutputStream(outfile));
    stream.write(o);
    o.close();

    X509CRL changedCrl = readCRL();

    Set<BigInteger> discoveredSerials = new HashSet<BigInteger>();

    for (X509CRLEntry entry : changedCrl.getRevokedCertificates()) {
        discoveredSerials.add(entry.getSerialNumber());
    }

    X509CRL originalCrl = new JcaX509CRLConverter().setProvider(BC).getCRL(holder);

    assertNotNull(changedCrl.getNextUpdate());

    long changedCrlUpdateDelta = changedCrl.getNextUpdate().getTime() - changedCrl.getThisUpdate().getTime();

    // We're allowing a tolerance of a few milliseconds to deal with minor timing issues
    long deltaTolerance = 3;
    long deltaDiff = changedCrlUpdateDelta - (oneHourHence.getTime() - oneHourAgo.getTime());

    assertTrue(Math.abs(deltaDiff) <= deltaTolerance);
    assertThat(changedCrl.getThisUpdate(), greaterThan(originalCrl.getThisUpdate()));

    assertEquals(newSerials, discoveredSerials);
    assertEquals(originalCrl.getIssuerX500Principal(), changedCrl.getIssuerX500Principal());

    ASN1ObjectIdentifier crlNumberOID = X509Extension.cRLNumber;
    byte[] oldCrlNumberBytes = originalCrl.getExtensionValue(crlNumberOID.getId());
    byte[] newCrlNumberBytes = changedCrl.getExtensionValue(crlNumberOID.getId());

    DEROctetString oldOctet = (DEROctetString) DERTaggedObject.fromByteArray(oldCrlNumberBytes);
    DEROctetString newOctet = (DEROctetString) DERTaggedObject.fromByteArray(newCrlNumberBytes);
    DERInteger oldNumber = (DERInteger) DERTaggedObject.fromByteArray(oldOctet.getOctets());
    DERInteger newNumber = (DERInteger) DERTaggedObject.fromByteArray(newOctet.getOctets());
    assertEquals(oldNumber.getValue().add(BigInteger.ONE), newNumber.getValue());

    ASN1ObjectIdentifier authorityKeyOID = X509Extension.authorityKeyIdentifier;
    byte[] oldAuthorityKeyId = originalCrl.getExtensionValue(authorityKeyOID.getId());
    byte[] newAuthorityKeyId = changedCrl.getExtensionValue(authorityKeyOID.getId());
    assertArrayEquals(oldAuthorityKeyId, newAuthorityKeyId);
}

From source file:org.candlepin.util.X509CRLStreamWriterTest.java

@Test
public void testModifyUpdatedTime() throws Exception {
    X509CRLHolder holder = createCRL();/*  w  ww.j  a va  2 s . c o  m*/
    File crlToChange = writeCRL(holder);

    Thread.sleep(1000);

    X509CRLStreamWriter stream = new X509CRLStreamWriter(crlToChange, (RSAPrivateKey) keyPair.getPrivate(),
            (RSAPublicKey) keyPair.getPublic());
    stream.preScan(crlToChange).lock();
    OutputStream o = new BufferedOutputStream(new FileOutputStream(outfile));
    stream.write(o);
    o.close();

    X509CRL changedCrl = readCRL();
    X509CRL originalCrl = new JcaX509CRLConverter().setProvider(BC).getCRL(holder);

    assertTrue("Error: CRL thisUpdate field unmodified",
            originalCrl.getThisUpdate().before(changedCrl.getThisUpdate()));
}