use of org.xipki.security.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);
}
}
}
use of org.xipki.security.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;
}
use of org.xipki.security.CrlReason in project xipki by xipki.
the class X509Ca method revokeCertificate.
// method publishCrl
public X509CertWithRevocationInfo revokeCertificate(BigInteger serialNumber, CrlReason reason, Date invalidityTime, String msgId) throws OperationException {
if (caInfo.isSelfSigned() && caInfo.getSerialNumber().equals(serialNumber)) {
throw new OperationException(ErrorCode.NOT_PERMITTED, "insufficient permission to revoke CA certificate");
}
CrlReason tmpReason = reason;
if (tmpReason == null) {
tmpReason = CrlReason.UNSPECIFIED;
}
switch(tmpReason) {
case CA_COMPROMISE:
case AA_COMPROMISE:
case REMOVE_FROM_CRL:
throw new OperationException(ErrorCode.NOT_PERMITTED, "Insufficient permission revoke certificate with reason " + tmpReason.getDescription());
case UNSPECIFIED:
case KEY_COMPROMISE:
case AFFILIATION_CHANGED:
case SUPERSEDED:
case CESSATION_OF_OPERATION:
case CERTIFICATE_HOLD:
case PRIVILEGE_WITHDRAWN:
break;
default:
throw new RuntimeException("unknown CRL reason " + tmpReason);
}
// switch (reason)
AuditEvent event = newPerfAuditEvent(CaAuditConstants.TYPE_revoke_cert, msgId);
boolean successful = true;
try {
X509CertWithRevocationInfo ret = revokeCertificate0(serialNumber, reason, invalidityTime, false, event);
successful = (ret != null);
return ret;
} finally {
finish(event, successful);
}
}
use of org.xipki.security.CrlReason in project xipki by xipki.
the class BatchOcspQaStatusCmd method processOcspQuery.
// method execute0
private ValidationResult processOcspQuery(OcspQa ocspQa, String line, File messageDir, File detailsDir, URL serverUrl, X509Certificate respIssuer, X509Certificate issuerCert, IssuerHash issuerHash, RequestOptions requestOptions) throws Exception {
StringTokenizer tokens = new StringTokenizer(line, ",;:");
int count = tokens.countTokens();
BigInteger serialNumber;
OcspCertStatus status = null;
Date revTime = null;
try {
serialNumber = toBigInt(tokens.nextToken(), hex);
if (count > 1) {
String token = tokens.nextToken();
if ("unknown".equalsIgnoreCase(token)) {
status = OcspCertStatus.unknown;
} else if ("good".equalsIgnoreCase(token)) {
status = OcspCertStatus.good;
} else {
CrlReason reason = CrlReason.forNameOrText(token);
switch(reason) {
case AA_COMPROMISE:
status = OcspCertStatus.aACompromise;
break;
case CA_COMPROMISE:
status = OcspCertStatus.cACompromise;
break;
case AFFILIATION_CHANGED:
status = OcspCertStatus.affiliationChanged;
break;
case CERTIFICATE_HOLD:
status = OcspCertStatus.certificateHold;
break;
case CESSATION_OF_OPERATION:
status = OcspCertStatus.cessationOfOperation;
break;
case KEY_COMPROMISE:
status = OcspCertStatus.keyCompromise;
break;
case PRIVILEGE_WITHDRAWN:
status = OcspCertStatus.privilegeWithdrawn;
break;
case SUPERSEDED:
status = OcspCertStatus.superseded;
break;
case UNSPECIFIED:
status = OcspCertStatus.unspecified;
break;
default:
throw new Exception("invalid reason");
}
}
} else {
status = OcspCertStatus.good;
}
if (count > 2 && status != OcspCertStatus.good && status != OcspCertStatus.unknown) {
revTime = DateUtil.parseUtcTimeyyyyMMddhhmmss(tokens.nextToken());
}
} catch (Exception ex) {
LogUtil.warn(LOG, ex, "Could not parse line '" + line + "'");
throw new IllegalArgumentException("illegal line");
}
return processOcspQuery(ocspQa, serialNumber, status, revTime, messageDir, detailsDir, serverUrl, respIssuer, issuerCert, issuerHash, requestOptions);
}
use of org.xipki.security.CrlReason in project xipki by xipki.
the class CertStoreQueryExecutor method revokeSuspendedCert.
// method revokeCert
X509CertWithRevocationInfo revokeSuspendedCert(NameId ca, BigInteger serialNumber, CrlReason reason, boolean publishToDeltaCrlCache, CaIdNameMap idNameMap) throws OperationException, DataAccessException {
ParamUtil.requireNonNull("ca", ca);
ParamUtil.requireNonNull("serialNumber", serialNumber);
ParamUtil.requireNonNull("reason", reason);
X509CertWithRevocationInfo certWithRevInfo = getCertWithRevocationInfo(ca, serialNumber, idNameMap);
if (certWithRevInfo == null) {
LOG.warn("certificate with CA={} and serialNumber={} does not exist", ca.getName(), LogUtil.formatCsn(serialNumber));
return null;
}
CertRevocationInfo currentRevInfo = certWithRevInfo.getRevInfo();
if (currentRevInfo == null) {
throw new OperationException(ErrorCode.CERT_UNREVOKED, "certificate is not revoked");
}
CrlReason currentReason = currentRevInfo.getReason();
if (currentReason != CrlReason.CERTIFICATE_HOLD) {
throw new OperationException(ErrorCode.CERT_REVOKED, "certificate is revoked but not with reason " + CrlReason.CERTIFICATE_HOLD.getDescription());
}
long certId = certWithRevInfo.getCert().getCertId().longValue();
PreparedStatement ps = borrowPreparedStatement(SQLs.SQL_REVOKE_SUSPENDED_CERT);
try {
int idx = 1;
ps.setLong(idx++, System.currentTimeMillis() / 1000);
ps.setInt(idx++, reason.getCode());
ps.setLong(idx++, certId);
int count = ps.executeUpdate();
if (count != 1) {
String message = (count > 1) ? count + " rows modified, but exactly one is expected" : "no row is modified, but exactly one is expected";
throw new OperationException(ErrorCode.SYSTEM_FAILURE, message);
}
} catch (SQLException ex) {
throw datasource.translate(SQLs.SQL_REVOKE_CERT, ex);
} finally {
releaseDbResources(ps, null);
}
if (publishToDeltaCrlCache) {
publishToDeltaCrlCache(ca, certWithRevInfo.getCert().getCert().getSerialNumber());
}
currentRevInfo.setReason(reason);
return certWithRevInfo;
}
Aggregations