Search in sources :

Example 1 with CRLReason

use of org.bouncycastle.asn1.x509.CRLReason in project XobotOS by xamarin.

the class X509CRLEntryObject method toString.

public String toString() {
    StringBuffer buf = new StringBuffer();
    String nl = System.getProperty("line.separator");
    buf.append("      userCertificate: ").append(this.getSerialNumber()).append(nl);
    buf.append("       revocationDate: ").append(this.getRevocationDate()).append(nl);
    buf.append("       certificateIssuer: ").append(this.getCertificateIssuer()).append(nl);
    X509Extensions extensions = c.getExtensions();
    if (extensions != null) {
        Enumeration e = extensions.oids();
        if (e.hasMoreElements()) {
            buf.append("   crlEntryExtensions:").append(nl);
            while (e.hasMoreElements()) {
                DERObjectIdentifier oid = (DERObjectIdentifier) e.nextElement();
                X509Extension ext = extensions.getExtension(oid);
                if (ext.getValue() != null) {
                    byte[] octs = ext.getValue().getOctets();
                    ASN1InputStream dIn = new ASN1InputStream(octs);
                    buf.append("                       critical(").append(ext.isCritical()).append(") ");
                    try {
                        if (oid.equals(X509Extensions.ReasonCode)) {
                            buf.append(new CRLReason(DEREnumerated.getInstance(dIn.readObject()))).append(nl);
                        } else if (oid.equals(X509Extensions.CertificateIssuer)) {
                            buf.append("Certificate issuer: ").append(new GeneralNames((ASN1Sequence) dIn.readObject())).append(nl);
                        } else {
                            buf.append(oid.getId());
                            buf.append(" value = ").append(ASN1Dump.dumpAsString(dIn.readObject())).append(nl);
                        }
                    } catch (Exception ex) {
                        buf.append(oid.getId());
                        buf.append(" value = ").append("*****").append(nl);
                    }
                } else {
                    buf.append(nl);
                }
            }
        }
    }
    return buf.toString();
}
Also used : ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) Enumeration(java.util.Enumeration) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) X509Extension(org.bouncycastle.asn1.x509.X509Extension) X509Extensions(org.bouncycastle.asn1.x509.X509Extensions) CRLReason(org.bouncycastle.asn1.x509.CRLReason) DERObjectIdentifier(org.bouncycastle.asn1.DERObjectIdentifier) IOException(java.io.IOException) CRLException(java.security.cert.CRLException)

Example 2 with CRLReason

use of org.bouncycastle.asn1.x509.CRLReason in project xipki by xipki.

the class ImportCrl method importEntries.

private void importEntries(Connection conn, int caId) throws DataAccessException, ImportCrlException {
    AtomicLong maxId = new AtomicLong(datasource.getMax(conn, "CERT", "ID"));
    // import the revoked information
    Set<? extends X509CRLEntry> revokedCertList = crl.getRevokedCertificates();
    if (revokedCertList != null) {
        for (X509CRLEntry c : revokedCertList) {
            X500Principal issuer = c.getCertificateIssuer();
            BigInteger serial = c.getSerialNumber();
            if (issuer != null) {
                if (!x500PrincipalCaSubject.equals(issuer)) {
                    throw new ImportCrlException("invalid CRLEntry for certificate number " + serial);
                }
            }
            Date rt = c.getRevocationDate();
            Date rit = null;
            byte[] extnValue = c.getExtensionValue(Extension.invalidityDate.getId());
            if (extnValue != null) {
                extnValue = extractCoreValue(extnValue);
                ASN1GeneralizedTime genTime = DERGeneralizedTime.getInstance(extnValue);
                try {
                    rit = genTime.getDate();
                } catch (ParseException ex) {
                    throw new ImportCrlException(ex.getMessage(), ex);
                }
                if (rt.equals(rit)) {
                    rit = null;
                }
            }
            CrlReason reason = CrlReason.fromReason(c.getRevocationReason());
            String sql = null;
            try {
                if (reason == CrlReason.REMOVE_FROM_CRL) {
                    if (!isDeltaCrl) {
                        LOG.warn("ignore CRL entry with reason removeFromCRL in non-Delta CRL");
                    }
                    // delete the entry
                    sql = SQL_DELETE_CERT;
                    psDeleteCert.setInt(1, caId);
                    psDeleteCert.setString(2, serial.toString(16));
                    psDeleteCert.executeUpdate();
                    continue;
                }
                Long id = getId(caId, serial);
                PreparedStatement ps;
                int offset = 1;
                if (id == null) {
                    sql = SQL_INSERT_CERT_REV;
                    id = maxId.incrementAndGet();
                    ps = psInsertCertRev;
                    ps.setLong(offset++, id);
                    ps.setInt(offset++, caId);
                    ps.setString(offset++, serial.toString(16));
                } else {
                    sql = SQL_UPDATE_CERT_REV;
                    ps = psUpdateCertRev;
                }
                ps.setInt(offset++, 1);
                ps.setInt(offset++, reason.getCode());
                ps.setLong(offset++, rt.getTime() / 1000);
                if (rit != null) {
                    ps.setLong(offset++, rit.getTime() / 1000);
                } else {
                    ps.setNull(offset++, Types.BIGINT);
                }
                ps.setLong(offset++, System.currentTimeMillis() / 1000);
                if (ps == psUpdateCertRev) {
                    ps.setLong(offset++, id);
                }
                ps.executeUpdate();
            } catch (SQLException ex) {
                throw datasource.translate(sql, ex);
            }
        }
    }
    // import the certificates
    // extract the certificate
    byte[] extnValue = crl.getExtensionValue(ObjectIdentifiers.id_xipki_ext_crlCertset.getId());
    if (extnValue != null) {
        extnValue = extractCoreValue(extnValue);
        ASN1Set asn1Set = DERSet.getInstance(extnValue);
        final int n = asn1Set.size();
        for (int i = 0; i < n; i++) {
            ASN1Encodable asn1 = asn1Set.getObjectAt(i);
            ASN1Sequence seq = ASN1Sequence.getInstance(asn1);
            BigInteger serialNumber = ASN1Integer.getInstance(seq.getObjectAt(0)).getValue();
            Certificate cert = null;
            String profileName = null;
            final int size = seq.size();
            for (int j = 1; j < size; j++) {
                ASN1TaggedObject taggedObj = DERTaggedObject.getInstance(seq.getObjectAt(j));
                int tagNo = taggedObj.getTagNo();
                switch(tagNo) {
                    case 0:
                        cert = Certificate.getInstance(taggedObj.getObject());
                        break;
                    case 1:
                        profileName = DERUTF8String.getInstance(taggedObj.getObject()).getString();
                        break;
                    default:
                        break;
                }
            }
            if (cert == null) {
                continue;
            }
            if (!caSubject.equals(cert.getIssuer())) {
                LOG.warn("issuer not match (serial={}) in CRL Extension Xipki-CertSet, ignore it", LogUtil.formatCsn(serialNumber));
                continue;
            }
            if (!serialNumber.equals(cert.getSerialNumber().getValue())) {
                LOG.warn("serialNumber not match (serial={}) in CRL Extension Xipki-CertSet, ignore it", LogUtil.formatCsn(serialNumber));
                continue;
            }
            String certLogId = "(issuer='" + cert.getIssuer() + "', serialNumber=" + cert.getSerialNumber() + ")";
            addCertificate(maxId, caId, cert, profileName, certLogId);
        }
    } else {
        // cert dirs
        File certsDir = new File(certsDirName);
        if (!certsDir.exists()) {
            LOG.warn("the folder {} does not exist, ignore it", certsDirName);
            return;
        }
        if (!certsDir.isDirectory()) {
            LOG.warn("the path {} does not point to a folder, ignore it", certsDirName);
            return;
        }
        if (!certsDir.canRead()) {
            LOG.warn("the folder {} must not be read, ignore it", certsDirName);
            return;
        }
        File[] certFiles = certsDir.listFiles(new FilenameFilter() {

            @Override
            public boolean accept(File dir, String name) {
                return name.endsWith(".der") || name.endsWith(".crt");
            }
        });
        if (certFiles == null || certFiles.length == 0) {
            return;
        }
        for (File certFile : certFiles) {
            Certificate cert;
            try {
                byte[] encoded = IoUtil.read(certFile);
                cert = Certificate.getInstance(encoded);
            } catch (IllegalArgumentException | IOException ex) {
                LOG.warn("could not parse certificate {}, ignore it", certFile.getPath());
                continue;
            }
            String certLogId = "(file " + certFile.getName() + ")";
            addCertificate(maxId, caId, cert, null, certLogId);
        }
    }
}
Also used : SQLException(java.sql.SQLException) ASN1TaggedObject(org.bouncycastle.asn1.ASN1TaggedObject) ASN1GeneralizedTime(org.bouncycastle.asn1.ASN1GeneralizedTime) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DEROctetString(org.bouncycastle.asn1.DEROctetString) DERIA5String(org.bouncycastle.asn1.DERIA5String) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) FilenameFilter(java.io.FilenameFilter) X509CRLEntry(java.security.cert.X509CRLEntry) CrlReason(org.xipki.security.CrlReason) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) PreparedStatement(java.sql.PreparedStatement) IOException(java.io.IOException) Date(java.util.Date) AtomicLong(java.util.concurrent.atomic.AtomicLong) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) ASN1Set(org.bouncycastle.asn1.ASN1Set) AtomicLong(java.util.concurrent.atomic.AtomicLong) X500Principal(javax.security.auth.x500.X500Principal) BigInteger(java.math.BigInteger) ParseException(java.text.ParseException) File(java.io.File) X509Certificate(java.security.cert.X509Certificate) Certificate(org.bouncycastle.asn1.x509.Certificate) TBSCertificate(org.bouncycastle.asn1.x509.TBSCertificate)

Example 3 with CRLReason

use of org.bouncycastle.asn1.x509.CRLReason in project xipki by xipki.

the class OcspQa method checkSingleCert.

// method checkOcsp
private List<ValidationIssue> checkSingleCert(int index, SingleResp singleResp, IssuerHash issuerHash, OcspCertStatus expectedStatus, byte[] encodedCert, Date expectedRevTime, boolean extendedRevoke, Occurrence nextupdateOccurrence, Occurrence certhashOccurrence, ASN1ObjectIdentifier certhashAlg) {
    if (expectedStatus == OcspCertStatus.unknown || expectedStatus == OcspCertStatus.issuerUnknown) {
        certhashOccurrence = Occurrence.forbidden;
    }
    List<ValidationIssue> issues = new LinkedList<>();
    // issuer hash
    ValidationIssue issue = new ValidationIssue("OCSP.RESPONSE." + index + ".ISSUER", "certificate issuer");
    issues.add(issue);
    CertificateID certId = singleResp.getCertID();
    HashAlgo hashAlgo = HashAlgo.getInstance(certId.getHashAlgOID());
    if (hashAlgo == null) {
        issue.setFailureMessage("unknown hash algorithm " + certId.getHashAlgOID().getId());
    } else {
        if (!issuerHash.match(hashAlgo, certId.getIssuerNameHash(), certId.getIssuerKeyHash())) {
            issue.setFailureMessage("issuer not match");
        }
    }
    // status
    issue = new ValidationIssue("OCSP.RESPONSE." + index + ".STATUS", "certificate status");
    issues.add(issue);
    CertificateStatus singleCertStatus = singleResp.getCertStatus();
    OcspCertStatus status = null;
    Long revTimeSec = null;
    if (singleCertStatus == null) {
        status = OcspCertStatus.good;
    } else if (singleCertStatus instanceof RevokedStatus) {
        RevokedStatus revStatus = (RevokedStatus) singleCertStatus;
        revTimeSec = revStatus.getRevocationTime().getTime() / 1000;
        if (revStatus.hasRevocationReason()) {
            int reason = revStatus.getRevocationReason();
            if (extendedRevoke && reason == CrlReason.CERTIFICATE_HOLD.getCode() && revTimeSec == 0) {
                status = OcspCertStatus.unknown;
                revTimeSec = null;
            } else {
                CrlReason revocationReason = CrlReason.forReasonCode(reason);
                switch(revocationReason) {
                    case UNSPECIFIED:
                        status = OcspCertStatus.unspecified;
                        break;
                    case KEY_COMPROMISE:
                        status = OcspCertStatus.keyCompromise;
                        break;
                    case CA_COMPROMISE:
                        status = OcspCertStatus.cACompromise;
                        break;
                    case AFFILIATION_CHANGED:
                        status = OcspCertStatus.affiliationChanged;
                        break;
                    case SUPERSEDED:
                        status = OcspCertStatus.superseded;
                        break;
                    case CERTIFICATE_HOLD:
                        status = OcspCertStatus.certificateHold;
                        break;
                    case REMOVE_FROM_CRL:
                        status = OcspCertStatus.removeFromCRL;
                        break;
                    case PRIVILEGE_WITHDRAWN:
                        status = OcspCertStatus.privilegeWithdrawn;
                        break;
                    case AA_COMPROMISE:
                        status = OcspCertStatus.aACompromise;
                        break;
                    case CESSATION_OF_OPERATION:
                        status = OcspCertStatus.cessationOfOperation;
                        break;
                    default:
                        issue.setFailureMessage("should not reach here, unknown CRLReason " + revocationReason);
                        break;
                }
            }
        // end if
        } else {
            status = OcspCertStatus.rev_noreason;
        }
    // end if (revStatus.hasRevocationReason())
    } else if (singleCertStatus instanceof UnknownStatus) {
        status = extendedRevoke ? OcspCertStatus.issuerUnknown : OcspCertStatus.unknown;
    } else {
        issue.setFailureMessage("unknown certstatus: " + singleCertStatus.getClass().getName());
    }
    if (!issue.isFailed() && expectedStatus != status) {
        issue.setFailureMessage("is='" + status + "', but expected='" + expectedStatus + "'");
    }
    // revocation time
    issue = new ValidationIssue("OCSP.RESPONSE." + index + ".REVTIME", "certificate time");
    issues.add(issue);
    if (expectedRevTime != null) {
        if (revTimeSec == null) {
            issue.setFailureMessage("is='null', but expected='" + formatTime(expectedRevTime) + "'");
        } else if (revTimeSec != expectedRevTime.getTime() / 1000) {
            issue.setFailureMessage("is='" + formatTime(new Date(revTimeSec * 1000)) + "', but expected='" + formatTime(expectedRevTime) + "'");
        }
    }
    // nextUpdate
    Date nextUpdate = singleResp.getNextUpdate();
    issue = checkOccurrence("OCSP.RESPONSE." + index + ".NEXTUPDATE", nextUpdate, nextupdateOccurrence);
    issues.add(issue);
    Extension extension = singleResp.getExtension(ISISMTTObjectIdentifiers.id_isismtt_at_certHash);
    issue = checkOccurrence("OCSP.RESPONSE." + index + ".CERTHASH", extension, certhashOccurrence);
    issues.add(issue);
    if (extension != null) {
        ASN1Encodable extensionValue = extension.getParsedValue();
        CertHash certHash = CertHash.getInstance(extensionValue);
        ASN1ObjectIdentifier hashAlgOid = certHash.getHashAlgorithm().getAlgorithm();
        if (certhashAlg != null) {
            // certHash algorithm
            issue = new ValidationIssue("OCSP.RESPONSE." + index + ".CHASH.ALG", "certhash algorithm");
            issues.add(issue);
            ASN1ObjectIdentifier is = certHash.getHashAlgorithm().getAlgorithm();
            if (!certhashAlg.equals(is)) {
                issue.setFailureMessage("is '" + is.getId() + "', but expected '" + certhashAlg.getId() + "'");
            }
        }
        byte[] hashValue = certHash.getCertificateHash();
        if (encodedCert != null) {
            issue = new ValidationIssue("OCSP.RESPONSE." + index + ".CHASH.VALIDITY", "certhash validity");
            issues.add(issue);
            try {
                MessageDigest md = MessageDigest.getInstance(hashAlgOid.getId());
                byte[] expectedHashValue = md.digest(encodedCert);
                if (!Arrays.equals(expectedHashValue, hashValue)) {
                    issue.setFailureMessage("certhash does not match the requested certificate");
                }
            } catch (NoSuchAlgorithmException ex) {
                issue.setFailureMessage("NoSuchAlgorithm " + hashAlgOid.getId());
            }
        }
    // end if(encodedCert != null)
    }
    return issues;
}
Also used : CertHash(org.bouncycastle.asn1.isismtt.ocsp.CertHash) CertificateID(org.bouncycastle.cert.ocsp.CertificateID) HashAlgo(org.xipki.security.HashAlgo) CertificateStatus(org.bouncycastle.cert.ocsp.CertificateStatus) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ValidationIssue(org.xipki.common.qa.ValidationIssue) LinkedList(java.util.LinkedList) Date(java.util.Date) UnknownStatus(org.bouncycastle.cert.ocsp.UnknownStatus) Extension(org.bouncycastle.asn1.x509.Extension) RevokedStatus(org.bouncycastle.cert.ocsp.RevokedStatus) CrlReason(org.xipki.security.CrlReason) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) MessageDigest(java.security.MessageDigest) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 4 with CRLReason

use of org.bouncycastle.asn1.x509.CRLReason in project xipki by xipki.

the class X509Ca method revokeCertificate0.

// method removeCertificate0
private X509CertWithRevocationInfo revokeCertificate0(BigInteger serialNumber, CrlReason reason, Date invalidityTime, boolean force, AuditEvent event) throws OperationException {
    String hexSerial = LogUtil.formatCsn(serialNumber);
    event.addEventData(CaAuditConstants.NAME_serial, hexSerial);
    event.addEventData(CaAuditConstants.NAME_reason, reason.getDescription());
    if (invalidityTime != null) {
        event.addEventData(CaAuditConstants.NAME_invalidityTime, DateUtil.toUtcTimeyyyyMMddhhmmss(invalidityTime));
    }
    LOG.info("     START revokeCertificate: ca={}, serialNumber={}, reason={}, invalidityTime={}", caIdent, hexSerial, reason.getDescription(), invalidityTime);
    X509CertWithRevocationInfo revokedCert = null;
    CertRevocationInfo revInfo = new CertRevocationInfo(reason, new Date(), invalidityTime);
    revokedCert = certstore.revokeCertificate(caIdent, serialNumber, revInfo, force, shouldPublishToDeltaCrlCache(), caIdNameMap);
    if (revokedCert == null) {
        return null;
    }
    for (IdentifiedX509CertPublisher publisher : publishers()) {
        if (!publisher.isAsyn()) {
            boolean successful;
            try {
                successful = publisher.certificateRevoked(caCert, revokedCert.getCert(), revokedCert.getCertprofile(), revokedCert.getRevInfo());
            } catch (RuntimeException ex) {
                successful = false;
                LogUtil.error(LOG, ex, "could not publish revocation of certificate to the publisher " + publisher.getIdent());
            }
            if (successful) {
                continue;
            }
        }
        // end if
        Long certId = revokedCert.getCert().getCertId();
        try {
            certstore.addToPublishQueue(publisher.getIdent(), certId.longValue(), caIdent);
        } catch (Throwable th) {
            LogUtil.error(LOG, th, "could not add entry to PublishQueue");
        }
    }
    if (LOG.isInfoEnabled()) {
        LOG.info("SUCCESSFUL revokeCertificate: ca={}, serialNumber={}, reason={}, invalidityTime={}," + " revocationResult=REVOKED", caIdent, hexSerial, reason.getDescription(), invalidityTime);
    }
    return revokedCert;
}
Also used : CertRevocationInfo(org.xipki.security.CertRevocationInfo) DERPrintableString(org.bouncycastle.asn1.DERPrintableString) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) X509CertWithRevocationInfo(org.xipki.ca.server.impl.store.X509CertWithRevocationInfo) Date(java.util.Date)

Example 5 with CRLReason

use of org.bouncycastle.asn1.x509.CRLReason in project candlepin by candlepin.

the class X509CRLStreamWriter method add.

/**
 * Create an entry to be added to the CRL.
 *
 * @param serial
 * @param date
 * @param reason
 * @throws IOException if an entry fails to generate
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public void add(BigInteger serial, Date date, int reason) throws IOException {
    if (locked) {
        throw new IllegalStateException("Cannot add to a locked stream.");
    }
    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(new ASN1Integer(serial));
    v.add(new Time(date));
    CRLReason crlReason = CRLReason.getInstance(new ASN1Enumerated(reason));
    ExtensionsGenerator generator = new ExtensionsGenerator();
    generator.addExtension(Extension.reasonCode, false, crlReason);
    v.add(generator.generate());
    newEntries.add(new DERSequence(v));
}
Also used : DERSequence(org.bouncycastle.asn1.DERSequence) ASN1Enumerated(org.bouncycastle.asn1.ASN1Enumerated) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) DERGeneralizedTime(org.bouncycastle.asn1.DERGeneralizedTime) ASN1GeneralizedTime(org.bouncycastle.asn1.ASN1GeneralizedTime) DERUTCTime(org.bouncycastle.asn1.DERUTCTime) Time(org.bouncycastle.asn1.x509.Time) ASN1UTCTime(org.bouncycastle.asn1.ASN1UTCTime) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) CRLReason(org.bouncycastle.asn1.x509.CRLReason) ExtensionsGenerator(org.bouncycastle.asn1.x509.ExtensionsGenerator)

Aggregations

CrlReason (org.xipki.security.CrlReason)9 Date (java.util.Date)7 OperationException (org.xipki.ca.api.OperationException)7 DEROctetString (org.bouncycastle.asn1.DEROctetString)6 DERPrintableString (org.bouncycastle.asn1.DERPrintableString)6 BigInteger (java.math.BigInteger)5 ASN1Integer (org.bouncycastle.asn1.ASN1Integer)5 DERUTF8String (org.bouncycastle.asn1.DERUTF8String)5 IOException (java.io.IOException)4 PreparedStatement (java.sql.PreparedStatement)4 SQLException (java.sql.SQLException)4 ASN1Encodable (org.bouncycastle.asn1.ASN1Encodable)4 Extensions (org.bouncycastle.asn1.x509.Extensions)4 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)3 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)3 ASN1Sequence (org.bouncycastle.asn1.ASN1Sequence)3 X500Name (org.bouncycastle.asn1.x500.X500Name)3 AuthorityKeyIdentifier (org.bouncycastle.asn1.x509.AuthorityKeyIdentifier)3 Extension (org.bouncycastle.asn1.x509.Extension)3 CertRevocationInfo (org.xipki.security.CertRevocationInfo)3