Example usage for java.security.cert X509CRL getNextUpdate

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

Introduction

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

Prototype

public abstract Date getNextUpdate();

Source Link

Document

Gets the nextUpdate date from the CRL.

Usage

From source file:org.casbah.provider.openssl.OpenSslCAProvider.java

@Override
public X509CRL getLatestCrl(boolean generateCrl) throws CAProviderException {
    X509CRL result = null;
    if (generateCrl) {
        result = generateNewCrl();/*w w w  . ja v  a2 s  .co  m*/
    } else {
        try {
            result = loadCrlFromFile();
        } catch (FileNotFoundException fnfe) {
            result = generateNewCrl();
        } catch (CertificateException e) {
            throw new CAProviderException("Could not parse CRL file", e);
        } catch (CRLException e) {
            throw new CAProviderException("Could not parse CRL file", e);
        } catch (IOException e) {
            throw new CAProviderException("Could not parse CRL file", e);
        }
        if (result.getNextUpdate().before(new Date())) {
            result = generateNewCrl();
        }
    }
    return result;
}

From source file:org.cesecore.util.PKIXCertRevocationStatusChecker.java

private boolean isCorrectCRL(final CRL crl, final String issuerDN) {
    if (!(crl instanceof X509CRL)) {
        return false;
    }//from   w  w w  .  j a  va 2s .  c o  m

    X509CRL x509crl = (X509CRL) crl;
    if (!StringUtils.equals(issuerDN, CertTools.getIssuerDN(x509crl))) {
        return false;
    }

    final Date now = new Date(System.currentTimeMillis());
    final Date nextUpdate = x509crl.getNextUpdate();
    if (nextUpdate != null) {
        if (nextUpdate.after(now)) {
            return true;
        }

        if (log.isDebugEnabled()) {
            log.debug("CRL issued by " + issuerDN + " is out of date");
        }
        return false;
    }

    final Date thisUpdate = x509crl.getThisUpdate();
    if (thisUpdate != null) {
        final GregorianCalendar gc = new GregorianCalendar();
        gc.setTime(now);
        gc.add(Calendar.HOUR, 1);
        final Date expire = gc.getTime();

        if (expire.before(now)) {
            if (log.isDebugEnabled()) {
                log.debug("Could not find when CRL issued by " + issuerDN
                        + " should be updated and this CRL is over one hour old. Not using it");
            }
            return false;
        }

        log.warn("Could not find when CRL issued by " + issuerDN
                + " should be updated, but this CRL was issued less than an hour ago, so we are using it");
        return true;
    }

    if (log.isDebugEnabled()) {
        log.debug("Could not check issuance time for CRL issued by " + issuerDN);
    }
    return false;
}

From source file:org.jasig.cas.adaptors.x509.authentication.handler.support.AbstractCRLRevocationChecker.java

/** {@inheritDoc} */
public void check(final X509Certificate cert) throws GeneralSecurityException {
    if (cert == null) {
        throw new IllegalArgumentException("Certificate cannot be null.");
    }//  w w  w .  j a v  a2  s.  co m
    if (log.isDebugEnabled()) {
        log.debug("Evaluating certificate revocation status for " + CertUtils.toString(cert));
    }
    final X509CRL crl = getCRL(cert);
    if (crl == null) {
        log.warn("CRL data is not available for " + CertUtils.toString(cert));
        this.unavailableCRLPolicy.apply(null);
        return;
    }
    if (CertUtils.isExpired(crl)) {
        log.warn("CRL data expired on " + crl.getNextUpdate());
        this.expiredCRLPolicy.apply(crl);
    }
    final X509CRLEntry entry = crl.getRevokedCertificate(cert);
    if (entry != null) {
        throw new RevokedCertificateException(entry);
    }
}

From source file:org.jasig.cas.adaptors.x509.authentication.handler.support.ThresholdExpiredCRLRevocationPolicy.java

/**
 * The CRL next update time is compared against the current time with the threshold
 * applied and rejected if and only if the next update time is in the past.
 *
 * @param crl CRL instance to evaluate./* w w w.j a v a  2 s .  co  m*/
 *
 * @throws ExpiredCRLException On expired CRL data.
 *
 * @see org.jasig.cas.adaptors.x509.authentication.handler.support.RevocationPolicy#apply(java.lang.Object)
 */
public void apply(final X509CRL crl) throws GeneralSecurityException {
    final Calendar cutoff = Calendar.getInstance();
    if (CertUtils.isExpired(crl, cutoff.getTime())) {
        cutoff.add(Calendar.SECOND, -this.threshold);
        if (CertUtils.isExpired(crl, cutoff.getTime())) {
            throw new ExpiredCRLException(crl.toString(), cutoff.getTime(), this.threshold);
        }
        log.info(String.format("CRL expired on %s but is within threshold period, %s seconds.",
                crl.getNextUpdate(), this.threshold));
    }
}

From source file:org.viafirma.nucleo.validacion.CrlCache.java

/**
 * Retorna las crls asociadas al certificado actual en caso de que existan y no esten caducadas.
 * //ww  w.j av  a2s .c om
 * @param certificadoX509 Certificado para el que deseamos recuperar las crls.
 * @return Listado de crls asociado, null si no hay crls vlidas asociadas.
 */
public List<X509CRL> getCrlsFrom(X509Certificate certificadoX509) {
    String name = certificadoX509.getSubjectDN().getName();
    if (cacheCrlsForCertificate.containsKey(name)) {
        // Hay CRLs en la cache. comprobamos que su validez es correcta.
        List<X509CRL> listTemp = cacheCrlsForCertificate.get(name);
        if (listTemp.isEmpty()) {
            // No hay crls asociadas a este certificado.
            return null;
        } else {
            Date ahora = new Date();
            // Comprobamos que todas las CRLS estan en fecha correcta
            for (X509CRL crl : listTemp) {
                Date nextUpdate = crl.getNextUpdate();
                // Si la crl no informa de su proxima actualizacin requerida o la actualizacin ya es necesaria
                if (nextUpdate == null || nextUpdate.compareTo(ahora) < 0) {
                    // Algunas de las crls asociadas a este certificado estan caducadas,
                    // Las eliminamos de la cache para que se fuerce su recarga.
                    cacheCrlsForCertificate.remove(name);
                    return null;
                }
            }
            // OK. Existen Crls y no estan caducadas.
            return listTemp;
        }
    } else {
        return null;
    }
}

From source file:org.viafirma.nucleo.validacion.CRLUtil.java

/**
 * Retorna el listado de CRLs para los certificados que tienen informacin
 * correcta sobre sus puntos de distrubicin. 1.- Recupera las urls de los
 * puntos de distribucin de crls. 2.- Se descarga todas las crls.
 * /*from   w  w w .ja  v a 2s  . c o m*/
 * @param certificadoX509
 * @return
 * @throws NoSuchProviderException
 * @throws CertificateException
 */
private List<X509CRL> getCrlsPuntoDistribucion(X509Certificate certificadoX509)
        throws CertificateException, NoSuchProviderException {
    CertificateFactory factoriaCertificados = CertificateFactory.getInstance("X.509",
            BouncyCastleProvider.PROVIDER_NAME);
    List<String> urls = null;
    // recuperos los puntos de distribucin definidos del certificado.
    urls = getCrlPuntosDeDistribucion(certificadoX509);
    List<X509CRL> crls = new LinkedList<X509CRL>();
    if (urls != null) {
        // itero sobre las urls para ir obteniendo los listados
        for (String hostURL : urls) {
            log.debug("url ->" + hostURL);
            try {
                if (hostURL == null) {
                    log.debug("La url de la crl no es correcta.");

                } else if (!hostURL.startsWith("http:")) {
                    log.debug("La url de la crl no es correcta. " + hostURL);
                } else {
                    InputStream ioCrl = getIoCrlFromUrl(hostURL);

                    // leo el io para generar un fichero de crl
                    X509CRL crl = (X509CRL) factoriaCertificados.generateCRL(ioCrl);
                    if (crl != null) {
                        crls.add(crl);
                        // log.debug("CRLer -->" + crl.get());
                        log.debug("Effective   From -->" + crl.getThisUpdate());
                        log.debug("Nextate    -->" + crl.getNextUpdate());
                    } else {
                        log.debug("No se puede recuperar o no es un cert valido " + hostURL);
                    }
                    try {
                        ioCrl.close();
                    } catch (Exception e) {
                        // No se ha podido cerrar la conexin con la crl, sin importancia.
                    } // no importa si no podemos cerrar la conexin(
                      // significa que ya esta cerrada)
                }
            } catch (CRLException e) {
                log.warn(
                        "no se ha podido conectar a host para descargar las crls, en este momento no estan disponibles."
                                + e.getMessage(),
                        e);
                // e.printStackTrace();
            } catch (Exception e) {
                log.warn(
                        "no se ha podido conectar a host para descargar las crls, en este momento no estan disponibles."
                                + e.getMessage(),
                        e);
                e.printStackTrace();
            }
        }
    }
    return crls;
}

From source file:org.viafirma.nucleo.validacion.CRLUtil.java

/**
 * Recupera el listado de Crls obtenidas desde el LDAP. 
 * TODO: Separar cada implementacin en un IMPL concreto que tenga que cumplir con una interfaz
 * para resolver las crls y para parsear el certificado 
 * NOTA: para utilizar de forma oficial la validazin de CRLs de la FNMT es necesario firmar un convenio.
 * //w w  w .java2  s .c o m
 * @param certificadoX509
 * @return
 */
private List<X509CRL> getCrlLDAPFNMT(X509Certificate certificadoX509) {
    List<X509CRL> crls = new LinkedList<X509CRL>();
    // ********************************************************************************
    // si es un certiticado de la FNMT hay que acceder al ldap para
    // recuperar las crls.
    try {
        CertificateFactory factoriaCertificados = CertificateFactory.getInstance("X.509",
                BouncyCastleProvider.PROVIDER_NAME);
        // es un certificado de la FNMT. el procesamiento es diferente
        // al resto, es atacando a un LDAP
        // recuperamos del LDAP el certificado
        // NOTA: Esta url es solo para pruebas, para utilizar de forma
        // oficial la validazin de CRLs de la FNMT es necesario firmar un
        // convenio
        // ldap-2.cert.fnmt.es:389
        InputStream ioCrl = getIoCrlFromFNMTLDAP(certificadoX509);
        if (ioCrl != null) {
            // la crl del fichero actual esta publicada, recuperamos la crl
            // leo el io para generar un fichero de crl
            System.out.println("***ioCrl:" + ioCrl);
            X509CRL crl = (X509CRL) factoriaCertificados.generateCRL(ioCrl);
            System.out.println("***Despues deioCrl:" + crl);
            try {
                if (crl != null) {
                    crls.add(crl);
                    System.out.println("***3:" + crl.getIssuerDN());
                    log.debug("CRLer     -->" + crl.getIssuerDN());
                    log.debug("Effective   From -->" + crl.getThisUpdate());
                    log.debug("Nextate    -->" + crl.getNextUpdate());
                    crls.add(crl);
                } else {
                    log.debug("No se puede recuperar o no es un cert valido .");
                }

                ioCrl.close();
            } catch (Throwable e) {
                log.warn("Problemas al recuperar la crl ." + e.getMessage());
                e.printStackTrace();
            } // no importa si no podemos cerrar la conexin( significa
              // que ya esta cerrada)
        } else {
            log.error("No se ha recuperado la crl.");
        }
    } catch (CRLException e) {
        log.warn("No se puede recuperar la crl." + e.getMessage());
    } catch (Throwable e) {
        e.printStackTrace();
    }
    return crls;
}

From source file:org.wso2.carbon.identity.certificateauthority.crl.CrlFactory.java

/**
 * creates and store a crl in db for the given tenant
 *
 * @param tenantId tenant id/*from  w ww . j av  a  2s . c om*/
 * @throws Exception
 */
public void createAndStoreCrl(int tenantId) throws Exception {
    X509CRL crl = createFullCrl(tenantId);
    CrlDataHolderDao crlDataHolderDao = new CrlDataHolderDao();
    RevocationDAO revocationDAO = new RevocationDAO();
    revocationDAO.removeActivedCertificates();
    int fullnumber = crlDataHolderDao.findHighestCrlNumber(tenantId, false);
    int deltanumber = crlDataHolderDao.findHighestCrlNumber(tenantId, true);
    // nextCrlNumber: The highest number of last CRL (full or delta) and increased by 1 (both full CRLs and deltaCRLs share the same series of CRL Number)
    int nextCrlNumber = ((fullnumber > deltanumber) ? fullnumber : deltanumber) + 1;

    crlDataHolderDao.addCRL(crl, tenantId, crl.getThisUpdate(), crl.getNextUpdate(), nextCrlNumber, -1);

}

From source file:org.wso2.carbon.identity.certificateauthority.crl.CrlFactory.java

/**
 * create and store a delta crl in database
 *
 * @param tenantId id of the tenant//from  w w w. ja va2  s.c  o m
 * @throws Exception
 */
public void createAndStoreDeltaCrl(int tenantId) throws Exception {
    X509CRL crl = creteDeltaCrl(tenantId);
    if (crl != null) {
        CrlDataHolderDao crlDataHolderDao = new CrlDataHolderDao();
        int fullnumber = crlDataHolderDao.findHighestCrlNumber(tenantId, false);
        int deltanumber = crlDataHolderDao.findHighestCrlNumber(tenantId, true);
        // nextCrlNumber: The highest number of last CRL (full or delta) and increased by 1 (both full CRLs and deltaCRLs share the same series of CRL Number)
        int nextCrlNumber = ((fullnumber > deltanumber) ? fullnumber : deltanumber) + 1;
        crlDataHolderDao.addCRL(crl, tenantId, crl.getThisUpdate(), crl.getNextUpdate(), nextCrlNumber, 1);
    } else {
        log.info("Error while creating delta crl for tenant " + tenantId);
    }
}

From source file:org.xdi.oxauth.cert.validation.CRLCertificateVerifier.java

private boolean validateCRL(X509CRL x509crl, X509Certificate certificate, X509Certificate issuerCertificate,
        Date validationDate) {//from w w  w.j a  v  a2 s .c  o m
    Principal subjectX500Principal = certificate.getSubjectX500Principal();

    if (x509crl == null) {
        log.error("No CRL found for certificate '" + subjectX500Principal + "'");
        return false;
    }

    if (log.isTraceEnabled()) {
        try {
            log.trace("CRL number: " + getCrlNumber(x509crl));
        } catch (IOException ex) {
            log.error("Failed to get CRL number", ex);
        }
    }

    if (!x509crl.getIssuerX500Principal().equals(issuerCertificate.getSubjectX500Principal())) {
        log.error("The CRL must be signed by the issuer '" + subjectX500Principal
                + "' but instead is signed by '" + x509crl.getIssuerX500Principal() + "'");
        return false;
    }

    try {
        x509crl.verify(issuerCertificate.getPublicKey());
    } catch (Exception ex) {
        log.error("The signature verification for CRL cannot be performed", ex);
        return false;
    }

    log.debug("CRL validationDate: " + validationDate);
    log.debug("CRL nextUpdate: " + x509crl.getThisUpdate());
    log.debug("CRL thisUpdate: " + x509crl.getNextUpdate());

    if (x509crl.getNextUpdate() != null && validationDate.after(x509crl.getNextUpdate())) {
        log.error("CRL is too old");
        return false;
    }

    if (issuerCertificate.getKeyUsage() == null) {
        log.error("There is no KeyUsage extension for certificate '" + subjectX500Principal + "'");
        return false;
    }

    if (!issuerCertificate.getKeyUsage()[6]) {
        log.error("cRLSign bit is not set for CRL certificate'" + subjectX500Principal + "'");
        return false;
    }

    return true;

}