List of usage examples for org.bouncycastle.asn1.x509 IssuingDistributionPoint IssuingDistributionPoint
public IssuingDistributionPoint(DistributionPointName distributionPoint, boolean onlyContainsUserCerts, boolean onlyContainsCACerts, ReasonFlags onlySomeReasons, boolean indirectCRL, boolean onlyContainsAttributeCerts)
From source file:org.cesecore.certificates.ca.X509CA.java
License:Open Source License
/** * Generate a CRL or a deltaCRL/*from www . j a v a 2 s . c o m*/ * * @param certs * list of revoked certificates * @param crlnumber * CRLNumber for this CRL * @param isDeltaCRL * true if we should generate a DeltaCRL * @param basecrlnumber * caseCRLNumber for a delta CRL, use 0 for full CRLs * @param certProfile * certificate profile for CRL Distribution point in the CRL, or null * @return CRL * @throws CryptoTokenOfflineException * @throws IllegalCryptoTokenException * @throws IOException * @throws SignatureException * @throws NoSuchProviderException * @throws InvalidKeyException * @throws CRLException * @throws NoSuchAlgorithmException */ private X509CRLHolder generateCRL(CryptoToken cryptoToken, Collection<RevokedCertInfo> certs, long crlPeriod, int crlnumber, boolean isDeltaCRL, int basecrlnumber) throws CryptoTokenOfflineException, IllegalCryptoTokenException, IOException, SignatureException, NoSuchProviderException, InvalidKeyException, CRLException, NoSuchAlgorithmException { final String sigAlg = getCAInfo().getCAToken().getSignatureAlgorithm(); if (log.isDebugEnabled()) { log.debug("generateCRL(" + certs.size() + ", " + crlPeriod + ", " + crlnumber + ", " + isDeltaCRL + ", " + basecrlnumber); } // Make DNs final X509Certificate cacert = (X509Certificate) getCACertificate(); final X500Name issuer; if (cacert == null) { // This is an initial root CA, since no CA-certificate exists // (I don't think we can ever get here!!!) final X500NameStyle nameStyle; if (getUsePrintableStringSubjectDN()) { nameStyle = PrintableStringNameStyle.INSTANCE; } else { nameStyle = CeSecoreNameStyle.INSTANCE; } issuer = CertTools.stringToBcX500Name(getSubjectDN(), nameStyle, getUseLdapDNOrder()); } else { issuer = X500Name.getInstance(cacert.getSubjectX500Principal().getEncoded()); } final Date thisUpdate = new Date(); final Date nextUpdate = new Date(); nextUpdate.setTime(nextUpdate.getTime() + crlPeriod); final X509v2CRLBuilder crlgen = new X509v2CRLBuilder(issuer, thisUpdate); crlgen.setNextUpdate(nextUpdate); if (certs != null) { if (log.isDebugEnabled()) { log.debug("Adding " + certs.size() + " revoked certificates to CRL. Free memory=" + Runtime.getRuntime().freeMemory()); } final Iterator<RevokedCertInfo> it = certs.iterator(); while (it.hasNext()) { final RevokedCertInfo certinfo = (RevokedCertInfo) it.next(); crlgen.addCRLEntry(certinfo.getUserCertificate(), certinfo.getRevocationDate(), certinfo.getReason()); } if (log.isDebugEnabled()) { log.debug("Finished adding " + certs.size() + " revoked certificates to CRL. Free memory=" + Runtime.getRuntime().freeMemory()); } } // Authority key identifier if (getUseAuthorityKeyIdentifier() == true) { byte[] caSkid = (cacert != null ? CertTools.getSubjectKeyId(cacert) : null); if (caSkid != null) { // Use subject key id from CA certificate AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(caSkid); crlgen.addExtension(Extension.authorityKeyIdentifier, getAuthorityKeyIdentifierCritical(), aki); } else { // Generate from SHA1 of public key ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(cryptoToken .getPublicKey(getCAToken().getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CRLSIGN)) .getEncoded())); try { SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo( (ASN1Sequence) asn1InputStream.readObject()); AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki); crlgen.addExtension(Extension.authorityKeyIdentifier, getAuthorityKeyIdentifierCritical(), aki); } finally { asn1InputStream.close(); } } } // Authority Information Access final ASN1EncodableVector accessList = new ASN1EncodableVector(); if (getAuthorityInformationAccess() != null) { for (String url : getAuthorityInformationAccess()) { if (StringUtils.isNotEmpty(url)) { GeneralName accessLocation = new GeneralName(GeneralName.uniformResourceIdentifier, new DERIA5String(url)); accessList.add(new AccessDescription(AccessDescription.id_ad_caIssuers, accessLocation)); } } } if (accessList.size() > 0) { AuthorityInformationAccess authorityInformationAccess = AuthorityInformationAccess .getInstance(new DERSequence(accessList)); // "This CRL extension MUST NOT be marked critical." according to rfc4325 crlgen.addExtension(Extension.authorityInfoAccess, false, authorityInformationAccess); } // CRLNumber extension if (getUseCRLNumber() == true) { CRLNumber crlnum = new CRLNumber(BigInteger.valueOf(crlnumber)); crlgen.addExtension(Extension.cRLNumber, this.getCRLNumberCritical(), crlnum); } if (isDeltaCRL) { // DeltaCRLIndicator extension CRLNumber basecrlnum = new CRLNumber(BigInteger.valueOf(basecrlnumber)); crlgen.addExtension(Extension.deltaCRLIndicator, true, basecrlnum); } // CRL Distribution point URI and Freshest CRL DP if (getUseCrlDistributionPointOnCrl()) { String crldistpoint = getDefaultCRLDistPoint(); List<DistributionPoint> distpoints = generateDistributionPoints(crldistpoint); if (distpoints.size() > 0) { IssuingDistributionPoint idp = new IssuingDistributionPoint( distpoints.get(0).getDistributionPoint(), false, false, null, false, false); // According to the RFC, IDP must be a critical extension. // Nonetheless, at the moment, Mozilla is not able to correctly // handle the IDP extension and discards the CRL if it is critical. crlgen.addExtension(Extension.issuingDistributionPoint, getCrlDistributionPointOnCrlCritical(), idp); } if (!isDeltaCRL) { String crlFreshestDP = getCADefinedFreshestCRL(); List<DistributionPoint> freshestDistPoints = generateDistributionPoints(crlFreshestDP); if (freshestDistPoints.size() > 0) { CRLDistPoint ext = new CRLDistPoint((DistributionPoint[]) freshestDistPoints .toArray(new DistributionPoint[freshestDistPoints.size()])); // According to the RFC, the Freshest CRL extension on a // CRL must not be marked as critical. Therefore it is // hardcoded as not critical and is independent of // getCrlDistributionPointOnCrlCritical(). crlgen.addExtension(Extension.freshestCRL, false, ext); } } } final X509CRLHolder crl; if (log.isDebugEnabled()) { log.debug("Signing CRL. Free memory=" + Runtime.getRuntime().freeMemory()); } final String alias = getCAToken().getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CRLSIGN); try { final ContentSigner signer = new BufferingContentSigner(new JcaContentSignerBuilder(sigAlg) .setProvider(cryptoToken.getSignProviderName()).build(cryptoToken.getPrivateKey(alias)), 20480); crl = crlgen.build(signer); } catch (OperatorCreationException e) { // Very fatal error throw new RuntimeException("Can not create Jca content signer: ", e); } if (log.isDebugEnabled()) { log.debug("Finished signing CRL. Free memory=" + Runtime.getRuntime().freeMemory()); } // Verify using the CA certificate before returning // If we can not verify the issued CRL using the CA certificate we don't want to issue this CRL // because something is wrong... final PublicKey verifyKey; if (cacert != null) { verifyKey = cacert.getPublicKey(); if (log.isTraceEnabled()) { log.trace("Got the verify key from the CA certificate."); } } else { verifyKey = cryptoToken.getPublicKey(alias); if (log.isTraceEnabled()) { log.trace("Got the verify key from the CA token."); } } try { final ContentVerifierProvider verifier = new JcaContentVerifierProviderBuilder().build(verifyKey); if (!crl.isSignatureValid(verifier)) { throw new SignatureException("Error verifying CRL to be returned."); } } catch (OperatorCreationException e) { // Very fatal error throw new RuntimeException("Can not create Jca content signer: ", e); } catch (CertException e) { throw new SignatureException(e.getMessage(), e); } if (log.isDebugEnabled()) { log.debug("Returning CRL. Free memory=" + Runtime.getRuntime().freeMemory()); } return crl; }
From source file:org.ejbca.core.model.ca.caadmin.X509CA.java
License:Open Source License
/** Generate a CRL or a deltaCRL * //from w w w . java 2 s. c om * @param certs list of revoked certificates * @param crlnumber CRLNumber for this CRL * @param isDeltaCRL true if we should generate a DeltaCRL * @param basecrlnumber caseCRLNumber for a delta CRL, use 0 for full CRLs * @param certProfile certificate profile for CRL Distribution point in the CRL, or null * @return CRL * @throws CATokenOfflineException * @throws IllegalKeyStoreException * @throws IOException * @throws SignatureException * @throws NoSuchProviderException * @throws InvalidKeyException * @throws CRLException * @throws NoSuchAlgorithmException */ private CRL generateCRL(Collection<RevokedCertInfo> certs, long crlPeriod, int crlnumber, boolean isDeltaCRL, int basecrlnumber) throws CATokenOfflineException, IllegalKeyStoreException, IOException, SignatureException, NoSuchProviderException, InvalidKeyException, CRLException, NoSuchAlgorithmException { final String sigAlg = getCAInfo().getCATokenInfo().getSignatureAlgorithm(); if (log.isDebugEnabled()) { log.debug("generateCRL(" + certs.size() + ", " + crlPeriod + ", " + crlnumber + ", " + isDeltaCRL + ", " + basecrlnumber); } Date thisUpdate = new Date(); Date nextUpdate = new Date(); nextUpdate.setTime(nextUpdate.getTime() + crlPeriod); X509V2CRLGenerator crlgen = new X509V2CRLGenerator(); crlgen.setThisUpdate(thisUpdate); crlgen.setNextUpdate(nextUpdate); crlgen.setSignatureAlgorithm(sigAlg); // Make DNs X509Certificate cacert = (X509Certificate) getCACertificate(); if (cacert == null) { // This is an initial root CA, since no CA-certificate exists // (I don't think we can ever get here!!!) X509NameEntryConverter converter = null; if (getUsePrintableStringSubjectDN()) { converter = new PrintableStringEntryConverter(); } else { converter = new X509DefaultEntryConverter(); } X509Name caname = CertTools.stringToBcX509Name(getSubjectDN(), converter, getUseLdapDNOrder()); crlgen.setIssuerDN(caname); } else { crlgen.setIssuerDN(cacert.getSubjectX500Principal()); } if (certs != null) { Iterator<RevokedCertInfo> it = certs.iterator(); while (it.hasNext()) { RevokedCertInfo certinfo = (RevokedCertInfo) it.next(); crlgen.addCRLEntry(certinfo.getUserCertificate(), certinfo.getRevocationDate(), certinfo.getReason()); } } // Authority key identifier if (getUseAuthorityKeyIdentifier() == true) { SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo((ASN1Sequence) new ASN1InputStream( new ByteArrayInputStream(getCAToken().getPublicKey(SecConst.CAKEYPURPOSE_CRLSIGN).getEncoded())) .readObject()); AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki); crlgen.addExtension(X509Extensions.AuthorityKeyIdentifier.getId(), getAuthorityKeyIdentifierCritical(), aki); } // CRLNumber extension if (getUseCRLNumber() == true) { CRLNumber crlnum = new CRLNumber(BigInteger.valueOf(crlnumber)); crlgen.addExtension(X509Extensions.CRLNumber.getId(), this.getCRLNumberCritical(), crlnum); } if (isDeltaCRL) { // DeltaCRLIndicator extension CRLNumber basecrlnum = new CRLNumber(BigInteger.valueOf(basecrlnumber)); crlgen.addExtension(X509Extensions.DeltaCRLIndicator.getId(), true, basecrlnum); } // CRL Distribution point URI and Freshest CRL DP if (getUseCrlDistributionPointOnCrl()) { String crldistpoint = getDefaultCRLDistPoint(); List<DistributionPoint> distpoints = generateDistributionPoints(crldistpoint); if (distpoints.size() > 0) { IssuingDistributionPoint idp = new IssuingDistributionPoint( distpoints.get(0).getDistributionPoint(), false, false, null, false, false); // According to the RFC, IDP must be a critical extension. // Nonetheless, at the moment, Mozilla is not able to correctly // handle the IDP extension and discards the CRL if it is critical. crlgen.addExtension(X509Extensions.IssuingDistributionPoint.getId(), getCrlDistributionPointOnCrlCritical(), idp); } if (!isDeltaCRL) { String crlFreshestDP = getCADefinedFreshestCRL(); List<DistributionPoint> freshestDistPoints = generateDistributionPoints(crlFreshestDP); if (freshestDistPoints.size() > 0) { CRLDistPoint ext = new CRLDistPoint((DistributionPoint[]) freshestDistPoints .toArray(new DistributionPoint[freshestDistPoints.size()])); // According to the RFC, the Freshest CRL extension on a // CRL must not be marked as critical. Therefore it is // hardcoded as not critical and is independent of // getCrlDistributionPointOnCrlCritical(). crlgen.addExtension(X509Extensions.FreshestCRL.getId(), false, ext); } } } X509CRL crl; crl = crlgen.generate(getCAToken().getPrivateKey(SecConst.CAKEYPURPOSE_CRLSIGN), getCAToken().getProvider()); // Verify using the CA certificate before returning // If we can not verify the issued CRL using the CA certificate we don't want to issue this CRL // because something is wrong... PublicKey verifyKey; if (cacert != null) { verifyKey = cacert.getPublicKey(); } else { verifyKey = getCAToken().getPublicKey(SecConst.CAKEYPURPOSE_CRLSIGN); } crl.verify(verifyKey); return crl; }
From source file:org.signserver.validationservice.server.ValidationTestUtils.java
License:Open Source License
public static X509CRL genCRL(X509Certificate cacert, PrivateKey privKey, DistributionPoint dp, Collection<RevokedCertInfo> certs, int crlPeriod, int crlnumber) throws CATokenOfflineException, IllegalKeyStoreException, IOException, SignatureException, NoSuchProviderException, InvalidKeyException, CRLException, NoSuchAlgorithmException { final String sigAlg = "SHA1WithRSA"; boolean crlDistributionPointOnCrlCritical = true; boolean crlNumberCritical = false; Date thisUpdate = new Date(); Date nextUpdate = new Date(); // crlperiod is hours = crlperiod*60*60*1000 milliseconds nextUpdate.setTime(nextUpdate.getTime() + (crlPeriod * (long) (60 * 60 * 1000))); X509V2CRLGenerator crlgen = new X509V2CRLGenerator(); crlgen.setThisUpdate(thisUpdate);// www . j a v a 2 s . co m crlgen.setNextUpdate(nextUpdate); crlgen.setSignatureAlgorithm(sigAlg); CRLNumber crlnum = new CRLNumber(BigInteger.valueOf(crlnumber)); crlgen.addExtension(X509Extensions.CRLNumber.getId(), crlNumberCritical, crlnum); // Make DNs crlgen.setIssuerDN(cacert.getSubjectX500Principal()); if (certs != null) { Iterator<RevokedCertInfo> it = certs.iterator(); while (it.hasNext()) { RevokedCertInfo certinfo = it.next(); crlgen.addCRLEntry(certinfo.getUserCertificate(), certinfo.getRevocationDate(), certinfo.getReason()); } } // CRL Distribution point URI IssuingDistributionPoint idp = new IssuingDistributionPoint(dp.getDistributionPoint(), false, false, null, false, false); // According to the RFC, IDP must be a critical extension. // Nonetheless, at the moment, Mozilla is not able to correctly // handle the IDP extension and discards the CRL if it is critical. crlgen.addExtension(X509Extensions.IssuingDistributionPoint.getId(), crlDistributionPointOnCrlCritical, idp); X509CRL crl; crl = crlgen.generate(privKey, "BC"); // Verify before sending back crl.verify(cacert.getPublicKey()); return crl; }
From source file:org.xipki.ca.server.impl.X509CA.java
License:Open Source License
private X509CRL generateCRL(final boolean deltaCRL, final Date thisUpdate, final Date nextUpdate, final AuditEvent auditEvent) throws OperationException { X509CrlSignerEntryWrapper crlSigner = getCrlSigner(); if (crlSigner == null) { throw new OperationException(ErrorCode.INSUFFICIENT_PERMISSION, "CRL generation is not allowed"); }// w w w .ja v a 2 s. com LOG.info(" START generateCRL: ca={}, deltaCRL={}, nextUpdate={}", new Object[] { caInfo.getName(), deltaCRL, nextUpdate }); if (auditEvent != null) { auditEvent.addEventData(new AuditEventData("crlType", deltaCRL ? "DELTA_CRL" : "FULL_CRL")); if (nextUpdate != null) { String value; synchronized (dateFormat) { value = dateFormat.format(nextUpdate); } auditEvent.addEventData(new AuditEventData("nextUpdate", value)); } else { auditEvent.addEventData(new AuditEventData("nextUpdate", "NULL")); } } if (nextUpdate != null) { if (nextUpdate.getTime() - thisUpdate.getTime() < 10 * 60 * MS_PER_SECOND) { // less than 10 minutes throw new OperationException(ErrorCode.CRL_FAILURE, "nextUpdate and thisUpdate are too close"); } } CRLControl crlControl = crlSigner.getCRLControl(); boolean successfull = false; try { ConcurrentContentSigner _crlSigner = crlSigner.getSigner(); CRLControl control = crlSigner.getCRLControl(); boolean directCRL = _crlSigner == null; X500Name crlIssuer = directCRL ? caInfo.getPublicCAInfo().getX500Subject() : X500Name.getInstance(_crlSigner.getCertificate().getSubjectX500Principal().getEncoded()); X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(crlIssuer, thisUpdate); if (nextUpdate != null) { crlBuilder.setNextUpdate(nextUpdate); } BigInteger startSerial = BigInteger.ONE; final int numEntries = 100; X509CertWithDBCertId caCert = caInfo.getCertificate(); List<CertRevInfoWithSerial> revInfos; boolean isFirstCRLEntry = true; Date notExpireAt; if (control.isIncludeExpiredCerts()) { notExpireAt = new Date(0); } else { // 10 minutes buffer notExpireAt = new Date(thisUpdate.getTime() - 600L * MS_PER_SECOND); } do { if (deltaCRL) { revInfos = certstore.getCertificatesForDeltaCRL(caCert, startSerial, numEntries, control.isOnlyContainsCACerts(), control.isOnlyContainsUserCerts()); } else { revInfos = certstore.getRevokedCertificates(caCert, notExpireAt, startSerial, numEntries, control.isOnlyContainsCACerts(), control.isOnlyContainsUserCerts()); } BigInteger maxSerial = BigInteger.ONE; for (CertRevInfoWithSerial revInfo : revInfos) { BigInteger serial = revInfo.getSerial(); if (serial.compareTo(maxSerial) > 0) { maxSerial = serial; } CRLReason reason = revInfo.getReason(); Date revocationTime = revInfo.getRevocationTime(); Date invalidityTime = revInfo.getInvalidityTime(); if (invalidityTime != null && invalidityTime.equals(revocationTime)) { invalidityTime = null; } if (directCRL || isFirstCRLEntry == false) { if (invalidityTime != null) { crlBuilder.addCRLEntry(revInfo.getSerial(), revocationTime, reason.getCode(), invalidityTime); } else { crlBuilder.addCRLEntry(revInfo.getSerial(), revocationTime, reason.getCode()); } continue; } List<Extension> extensions = new ArrayList<>(3); if (reason != CRLReason.UNSPECIFIED) { Extension ext = createReasonExtension(reason.getCode()); extensions.add(ext); } if (invalidityTime != null) { Extension ext = createInvalidityDateExtension(invalidityTime); extensions.add(ext); } Extension ext = createCertificateIssuerExtension(caInfo.getPublicCAInfo().getX500Subject()); extensions.add(ext); Extensions asn1Extensions = new Extensions(extensions.toArray(new Extension[0])); crlBuilder.addCRLEntry(revInfo.getSerial(), revocationTime, asn1Extensions); isFirstCRLEntry = false; } // end for startSerial = maxSerial.add(BigInteger.ONE); } while (revInfos.size() >= numEntries); // end do BigInteger crlNumber = caInfo.nextCRLNumber(); if (auditEvent != null) { auditEvent.addEventData(new AuditEventData("crlNumber", crlNumber.toString())); } boolean onlyUserCerts = crlControl.isOnlyContainsUserCerts(); boolean onlyCACerts = crlControl.isOnlyContainsCACerts(); if (onlyUserCerts && onlyCACerts) { throw new RuntimeException("should not reach here, onlyUserCerts and onlyCACerts are both true"); } try { // AuthorityKeyIdentifier byte[] akiValues = directCRL ? caInfo.getPublicCAInfo().getSubjectKeyIdentifer() : crlSigner.getSubjectKeyIdentifier(); AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(akiValues); crlBuilder.addExtension(Extension.authorityKeyIdentifier, false, aki); // add extension CRL Number crlBuilder.addExtension(Extension.cRLNumber, false, new ASN1Integer(crlNumber)); // IssuingDistributionPoint if (onlyUserCerts == true || onlyCACerts == true || directCRL == false) { IssuingDistributionPoint idp = new IssuingDistributionPoint((DistributionPointName) null, // distributionPoint, onlyUserCerts, // onlyContainsUserCerts, onlyCACerts, // onlyContainsCACerts, (ReasonFlags) null, // onlySomeReasons, directCRL == false, // indirectCRL, false // onlyContainsAttributeCerts ); crlBuilder.addExtension(Extension.issuingDistributionPoint, true, idp); } } catch (CertIOException e) { final String message = "crlBuilder.addExtension"; if (LOG.isErrorEnabled()) { LOG.error(LogUtil.buildExceptionLogFormat(message), e.getClass().getName(), e.getMessage()); } LOG.debug(message, e); throw new OperationException(ErrorCode.INVALID_EXTENSION, e.getMessage()); } startSerial = BigInteger.ONE; if (deltaCRL == false && control.isEmbedsCerts()) // XiPKI extension { ASN1EncodableVector vector = new ASN1EncodableVector(); List<BigInteger> serials; do { serials = certstore.getCertSerials(caCert, notExpireAt, startSerial, numEntries, false, onlyCACerts, onlyUserCerts); BigInteger maxSerial = BigInteger.ONE; for (BigInteger serial : serials) { if (serial.compareTo(maxSerial) > 0) { maxSerial = serial; } X509CertificateInfo certInfo; try { certInfo = certstore.getCertificateInfoForSerial(caCert, serial); } catch (CertificateException e) { throw new OperationException(ErrorCode.SYSTEM_FAILURE, "CertificateException: " + e.getMessage()); } Certificate cert = Certificate.getInstance(certInfo.getCert().getEncodedCert()); ASN1EncodableVector v = new ASN1EncodableVector(); v.add(cert); String profileName = certInfo.getProfileName(); if (StringUtil.isNotBlank(profileName)) { v.add(new DERUTF8String(certInfo.getProfileName())); } ASN1Sequence certWithInfo = new DERSequence(v); vector.add(certWithInfo); } // end for startSerial = maxSerial.add(BigInteger.ONE); } while (serials.size() >= numEntries); // end fo try { crlBuilder.addExtension(ObjectIdentifiers.id_xipki_ext_crlCertset, false, new DERSet(vector)); } catch (CertIOException e) { throw new OperationException(ErrorCode.INVALID_EXTENSION, "CertIOException: " + e.getMessage()); } } ConcurrentContentSigner concurrentSigner = (_crlSigner == null) ? caInfo.getSigner(null) : _crlSigner; ContentSigner contentSigner; try { contentSigner = concurrentSigner.borrowContentSigner(); } catch (NoIdleSignerException e) { throw new OperationException(ErrorCode.SYSTEM_FAILURE, "NoIdleSignerException: " + e.getMessage()); } X509CRLHolder crlHolder; try { crlHolder = crlBuilder.build(contentSigner); } finally { concurrentSigner.returnContentSigner(contentSigner); } try { X509CRL crl = new X509CRLObject(crlHolder.toASN1Structure()); publishCRL(crl); successfull = true; LOG.info("SUCCESSFUL generateCRL: ca={}, crlNumber={}, thisUpdate={}", new Object[] { caInfo.getName(), crlNumber, crl.getThisUpdate() }); if (deltaCRL) { return crl; } // clean up the CRL try { cleanupCRLs(); } catch (Throwable t) { LOG.warn("could not cleanup CRLs.{}: {}", t.getClass().getName(), t.getMessage()); } return crl; } catch (CRLException e) { throw new OperationException(ErrorCode.CRL_FAILURE, "CRLException: " + e.getMessage()); } } finally { if (successfull == false) { LOG.info(" FAILED generateCRL: ca={}", caInfo.getName()); } } }
From source file:org.xipki.pki.ca.server.impl.X509Ca.java
License:Open Source License
private X509CRL doGenerateCrl(final boolean deltaCrl, final Date thisUpdate, final Date nextUpdate, final AuditEvent event, final String msgId) throws OperationException { X509CrlSignerEntryWrapper crlSigner = getCrlSigner(); if (crlSigner == null) { throw new OperationException(ErrorCode.NOT_PERMITTED, "CRL generation is not allowed"); }//from w w w . j a v a2 s . c o m String caName = caInfo.getName(); LOG.info(" START generateCrl: ca={}, deltaCRL={}, nextUpdate={}", caName, deltaCrl, nextUpdate); event.addEventData(CaAuditConstants.NAME_crlType, deltaCrl ? "DELTA_CRL" : "FULL_CRL"); if (nextUpdate == null) { event.addEventData(CaAuditConstants.NAME_nextUpdate, "null"); } else { event.addEventData(CaAuditConstants.NAME_nextUpdate, DateUtil.toUtcTimeyyyyMMddhhmmss(nextUpdate)); if (nextUpdate.getTime() - thisUpdate.getTime() < 10 * 60 * MS_PER_SECOND) { // less than 10 minutes throw new OperationException(ErrorCode.CRL_FAILURE, "nextUpdate and thisUpdate are too close"); } } CrlControl crlControl = crlSigner.getCrlControl(); boolean successful = false; try { ConcurrentContentSigner tmpCrlSigner = crlSigner.getSigner(); CrlControl control = crlSigner.getCrlControl(); boolean directCrl; X500Name crlIssuer; if (tmpCrlSigner == null) { directCrl = true; crlIssuer = caInfo.getPublicCaInfo().getX500Subject(); } else { directCrl = false; crlIssuer = X500Name .getInstance(tmpCrlSigner.getCertificate().getSubjectX500Principal().getEncoded()); } X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(crlIssuer, thisUpdate); if (nextUpdate != null) { crlBuilder.setNextUpdate(nextUpdate); } final int numEntries = 100; X509Cert caCert = caInfo.getCertificate(); List<CertRevInfoWithSerial> revInfos; boolean isFirstCrlEntry = true; Date notExpireAt; if (control.isIncludeExpiredCerts()) { notExpireAt = new Date(0); } else { // 10 minutes buffer notExpireAt = new Date(thisUpdate.getTime() - 600L * MS_PER_SECOND); } long startId = 1; do { if (deltaCrl) { revInfos = certstore.getCertsForDeltaCrl(caCert, startId, numEntries, control.isOnlyContainsCaCerts(), control.isOnlyContainsUserCerts()); } else { revInfos = certstore.getRevokedCerts(caCert, notExpireAt, startId, numEntries, control.isOnlyContainsCaCerts(), control.isOnlyContainsUserCerts()); } long maxId = 1; for (CertRevInfoWithSerial revInfo : revInfos) { if (revInfo.getId() > maxId) { maxId = revInfo.getId(); } CrlReason reason = revInfo.getReason(); if (crlControl.isExcludeReason() && reason != CrlReason.REMOVE_FROM_CRL) { reason = CrlReason.UNSPECIFIED; } Date revocationTime = revInfo.getRevocationTime(); Date invalidityTime = revInfo.getInvalidityTime(); switch (crlControl.getInvalidityDateMode()) { case FORBIDDEN: invalidityTime = null; break; case OPTIONAL: break; case REQUIRED: if (invalidityTime == null) { invalidityTime = revocationTime; } break; default: throw new RuntimeException("unknown TripleState: " + crlControl.getInvalidityDateMode()); } BigInteger serial = revInfo.getSerial(); LOG.debug("added cert ca={} serial={} to CRL", caName, serial); if (directCrl || !isFirstCrlEntry) { if (invalidityTime != null) { crlBuilder.addCRLEntry(serial, revocationTime, reason.getCode(), invalidityTime); } else { crlBuilder.addCRLEntry(serial, revocationTime, reason.getCode()); } continue; } List<Extension> extensions = new ArrayList<>(3); if (reason != CrlReason.UNSPECIFIED) { Extension ext = createReasonExtension(reason.getCode()); extensions.add(ext); } if (invalidityTime != null) { Extension ext = createInvalidityDateExtension(invalidityTime); extensions.add(ext); } Extension ext = createCertificateIssuerExtension(caInfo.getPublicCaInfo().getX500Subject()); extensions.add(ext); crlBuilder.addCRLEntry(serial, revocationTime, new Extensions(extensions.toArray(new Extension[0]))); isFirstCrlEntry = false; } // end for startId = maxId + 1; } while (revInfos.size() >= numEntries); // end do BigInteger crlNumber = caInfo.nextCrlNumber(); event.addEventData(CaAuditConstants.NAME_crlNumber, crlNumber); boolean onlyUserCerts = crlControl.isOnlyContainsUserCerts(); boolean onlyCaCerts = crlControl.isOnlyContainsCaCerts(); if (onlyUserCerts && onlyCaCerts) { throw new RuntimeException("should not reach here, onlyUserCerts and onlyCACerts are both true"); } try { // AuthorityKeyIdentifier byte[] akiValues = directCrl ? caInfo.getPublicCaInfo().getSubjectKeyIdentifer() : crlSigner.getSubjectKeyIdentifier(); AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(akiValues); crlBuilder.addExtension(Extension.authorityKeyIdentifier, false, aki); // add extension CRL Number crlBuilder.addExtension(Extension.cRLNumber, false, new ASN1Integer(crlNumber)); // IssuingDistributionPoint if (onlyUserCerts || onlyCaCerts || !directCrl) { IssuingDistributionPoint idp = new IssuingDistributionPoint((DistributionPointName) null, // distributionPoint, onlyUserCerts, // onlyContainsUserCerts, onlyCaCerts, // onlyContainsCACerts, (ReasonFlags) null, // onlySomeReasons, !directCrl, // indirectCRL, false); // onlyContainsAttributeCerts crlBuilder.addExtension(Extension.issuingDistributionPoint, true, idp); } // freshestCRL List<String> deltaCrlUris = getCaInfo().getPublicCaInfo().getDeltaCrlUris(); if (control.getDeltaCrlIntervals() > 0 && CollectionUtil.isNonEmpty(deltaCrlUris)) { CRLDistPoint cdp = CaUtil.createCrlDistributionPoints(deltaCrlUris, caInfo.getPublicCaInfo().getX500Subject(), crlIssuer); crlBuilder.addExtension(Extension.freshestCRL, false, cdp); } } catch (CertIOException ex) { LogUtil.error(LOG, ex, "crlBuilder.addExtension"); throw new OperationException(ErrorCode.INVALID_EXTENSION, ex); } addXipkiCertset(crlBuilder, deltaCrl, control, caCert, notExpireAt, onlyCaCerts, onlyUserCerts); ConcurrentContentSigner concurrentSigner = (tmpCrlSigner == null) ? caInfo.getSigner(null) : tmpCrlSigner; X509CRLHolder crlHolder; try { crlHolder = concurrentSigner.build(crlBuilder); } catch (NoIdleSignerException ex) { throw new OperationException(ErrorCode.SYSTEM_FAILURE, "NoIdleSignerException: " + ex.getMessage()); } try { X509CRL crl = X509Util.toX509Crl(crlHolder.toASN1Structure()); caInfo.getCaEntry().setNextCrlNumber(crlNumber.longValue() + 1); caInfo.commitNextCrlNo(); publishCrl(crl); successful = true; LOG.info("SUCCESSFUL generateCrl: ca={}, crlNumber={}, thisUpdate={}", caName, crlNumber, crl.getThisUpdate()); if (!deltaCrl) { // clean up the CRL cleanupCrlsWithoutException(msgId); } return crl; } catch (CRLException | CertificateException ex) { throw new OperationException(ErrorCode.CRL_FAILURE, ex); } } finally { if (!successful) { LOG.info(" FAILED generateCrl: ca={}", caName); } } }