use of org.openecard.bouncycastle.asn1.x509.Extensions in project xipki by xipki.
the class X509CmpRequestor method getCertTempExtensions.
private static Extensions getCertTempExtensions(byte[] authorityKeyIdentifier) throws CmpRequestorException {
AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(authorityKeyIdentifier);
byte[] encodedAki;
try {
encodedAki = aki.getEncoded();
} catch (IOException ex) {
throw new CmpRequestorException("could not encoded AuthorityKeyIdentifier", ex);
}
Extension extAki = new Extension(Extension.authorityKeyIdentifier, false, encodedAki);
Extensions certTempExts = new Extensions(extAki);
return certTempExts;
}
use of org.openecard.bouncycastle.asn1.x509.Extensions in project xipki by xipki.
the class X509CmpRequestor method buildRevokeCertRequest.
private PKIMessage buildRevokeCertRequest(RevokeCertRequest request) throws CmpRequestorException {
PKIHeader header = buildPkiHeader(null);
List<RevokeCertRequestEntry> requestEntries = request.getRequestEntries();
List<RevDetails> revDetailsArray = new ArrayList<>(requestEntries.size());
for (RevokeCertRequestEntry requestEntry : requestEntries) {
CertTemplateBuilder certTempBuilder = new CertTemplateBuilder();
certTempBuilder.setIssuer(requestEntry.getIssuer());
certTempBuilder.setSerialNumber(new ASN1Integer(requestEntry.getSerialNumber()));
byte[] aki = requestEntry.getAuthorityKeyIdentifier();
if (aki != null) {
Extensions certTempExts = getCertTempExtensions(aki);
certTempBuilder.setExtensions(certTempExts);
}
Date invalidityDate = requestEntry.getInvalidityDate();
int idx = (invalidityDate == null) ? 1 : 2;
Extension[] extensions = new Extension[idx];
try {
ASN1Enumerated reason = new ASN1Enumerated(requestEntry.getReason());
extensions[0] = new Extension(Extension.reasonCode, true, new DEROctetString(reason.getEncoded()));
if (invalidityDate != null) {
ASN1GeneralizedTime time = new ASN1GeneralizedTime(invalidityDate);
extensions[1] = new Extension(Extension.invalidityDate, true, new DEROctetString(time.getEncoded()));
}
} catch (IOException ex) {
throw new CmpRequestorException(ex.getMessage(), ex);
}
Extensions exts = new Extensions(extensions);
RevDetails revDetails = new RevDetails(certTempBuilder.build(), exts);
revDetailsArray.add(revDetails);
}
RevReqContent content = new RevReqContent(revDetailsArray.toArray(new RevDetails[0]));
PKIBody body = new PKIBody(PKIBody.TYPE_REVOCATION_REQ, content);
return new PKIMessage(header, body);
}
use of org.openecard.bouncycastle.asn1.x509.Extensions in project xipki by xipki.
the class X509Ca method generateCrl0.
private X509CRL generateCrl0(boolean deltaCrl, Date thisUpdate, Date nextUpdate, AuditEvent event, String msgId) throws OperationException {
X509CrlSignerEntryWrapper crlSigner = getCrlSigner();
if (crlSigner == null) {
throw new OperationException(ErrorCode.NOT_PERMITTED, "CRL generation is not allowed");
}
LOG.info(" START generateCrl: ca={}, deltaCRL={}, nextUpdate={}", caIdent, 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;
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;
// we have to cache the serial entries to sort them
List<CertRevInfoWithSerial> allRevInfos = new LinkedList<>();
List<CertRevInfoWithSerial> revInfos;
do {
if (deltaCrl) {
revInfos = certstore.getCertsForDeltaCrl(caIdent, startId, numEntries, control.isOnlyContainsCaCerts(), control.isOnlyContainsUserCerts());
} else {
revInfos = certstore.getRevokedCerts(caIdent, notExpireAt, startId, numEntries, control.isOnlyContainsCaCerts(), control.isOnlyContainsUserCerts());
}
allRevInfos.addAll(revInfos);
long maxId = 1;
for (CertRevInfoWithSerial revInfo : revInfos) {
if (revInfo.getId() > maxId) {
maxId = revInfo.getId();
}
}
// end for
startId = maxId + 1;
} while (// end do
revInfos.size() >= numEntries);
if (revInfos != null) {
// free the memory
revInfos.clear();
}
// sort the list by SerialNumber ASC
Collections.sort(allRevInfos);
boolean isFirstCrlEntry = true;
for (CertRevInfoWithSerial revInfo : allRevInfos) {
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", caIdent, 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;
}
// free the memory
allRevInfos.clear();
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(// distributionPoint,
(DistributionPointName) null, // onlyContainsUserCerts,
onlyUserCerts, // onlyContainsCACerts,
onlyCaCerts, // onlySomeReasons,
(ReasonFlags) null, // indirectCRL,
!directCrl, // onlyContainsAttributeCerts
false);
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, notExpireAt, onlyCaCerts, onlyUserCerts);
ConcurrentContentSigner concurrentSigner = (tmpCrlSigner == null) ? caInfo.getSigner(null) : tmpCrlSigner;
ConcurrentBagEntrySigner signer0;
try {
signer0 = concurrentSigner.borrowSigner();
} catch (NoIdleSignerException ex) {
throw new OperationException(ErrorCode.SYSTEM_FAILURE, "NoIdleSignerException: " + ex.getMessage());
}
X509CRLHolder crlHolder;
try {
crlHolder = crlBuilder.build(signer0.value());
} finally {
concurrentSigner.requiteSigner(signer0);
}
try {
X509CRL crl = X509Util.toX509Crl(crlHolder.toASN1Structure());
caInfo.getCaEntry().setNextCrlNumber(crlNumber.longValue() + 1);
caManager.commitNextCrlNo(caIdent, caInfo.getCaEntry().getNextCrlNumber());
publishCrl(crl);
successful = true;
LOG.info("SUCCESSFUL generateCrl: ca={}, crlNumber={}, thisUpdate={}", caIdent, 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={}", caIdent);
}
}
}
use of org.openecard.bouncycastle.asn1.x509.Extensions in project xipki by xipki.
the class RestImpl method service.
public RestResponse service(String path, AuditEvent event, byte[] request, HttpRequestMetadataRetriever httpRetriever) {
event.setApplicationName(CaAuditConstants.APPNAME);
event.setName(CaAuditConstants.NAME_PERF);
event.addEventData(CaAuditConstants.NAME_reqType, RequestType.REST.name());
String msgId = RandomUtil.nextHexLong();
event.addEventData(CaAuditConstants.NAME_mid, msgId);
AuditLevel auditLevel = AuditLevel.INFO;
AuditStatus auditStatus = AuditStatus.SUCCESSFUL;
String auditMessage = null;
try {
if (responderManager == null) {
String message = "responderManager in servlet not configured";
LOG.error(message);
throw new HttpRespAuditException(HttpResponseStatus.INTERNAL_SERVER_ERROR, null, message, AuditLevel.ERROR, AuditStatus.FAILED);
}
String caName = null;
String command = null;
X509Ca ca = null;
if (path.length() > 1) {
// the first char is always '/'
String coreUri = path;
int sepIndex = coreUri.indexOf('/', 1);
if (sepIndex == -1 || sepIndex == coreUri.length() - 1) {
String message = "invalid path " + path;
LOG.error(message);
throw new HttpRespAuditException(HttpResponseStatus.NOT_FOUND, null, message, AuditLevel.ERROR, AuditStatus.FAILED);
}
// skip also the first char ('/')
String caAlias = coreUri.substring(1, sepIndex);
command = coreUri.substring(sepIndex + 1);
caName = responderManager.getCaNameForAlias(caAlias);
if (caName == null) {
caName = caAlias.toLowerCase();
}
ca = ((X509CaCmpResponderImpl) responderManager.getX509CaResponder(caName)).getCa();
}
if (caName == null || ca == null || ca.getCaInfo().getStatus() != CaStatus.ACTIVE) {
String message;
if (caName == null) {
message = "no CA is specified";
} else if (ca == null) {
message = "unknown CA '" + caName + "'";
} else {
message = "CA '" + caName + "' is out of service";
}
LOG.warn(message);
throw new HttpRespAuditException(HttpResponseStatus.NOT_FOUND, null, message, AuditLevel.INFO, AuditStatus.FAILED);
}
event.addEventData(CaAuditConstants.NAME_ca, ca.getCaIdent().getName());
event.addEventType(command);
RequestorInfo requestor;
// Retrieve the user:password
String hdrValue = httpRetriever.getHeader("Authorization");
if (hdrValue != null && hdrValue.startsWith("Basic ")) {
String user = null;
byte[] password = null;
if (hdrValue.length() > 6) {
String b64 = hdrValue.substring(6);
byte[] userPwd = Base64.decodeFast(b64);
int idx = -1;
for (int i = 0; i < userPwd.length; i++) {
if (userPwd[i] == ':') {
idx = i;
break;
}
}
if (idx != -1 && idx < userPwd.length - 1) {
user = new String(Arrays.copyOfRange(userPwd, 0, idx));
password = Arrays.copyOfRange(userPwd, idx + 1, userPwd.length);
}
}
if (user == null) {
throw new HttpRespAuditException(HttpResponseStatus.UNAUTHORIZED, "invalid Authorization information", AuditLevel.INFO, AuditStatus.FAILED);
}
NameId userIdent = ca.authenticateUser(user, password);
if (userIdent == null) {
throw new HttpRespAuditException(HttpResponseStatus.UNAUTHORIZED, "could not authenticate user", AuditLevel.INFO, AuditStatus.FAILED);
}
requestor = ca.getByUserRequestor(userIdent);
} else {
X509Certificate clientCert = httpRetriever.getTlsClientCert();
if (clientCert == null) {
throw new HttpRespAuditException(HttpResponseStatus.UNAUTHORIZED, null, "no client certificate", AuditLevel.INFO, AuditStatus.FAILED);
}
requestor = ca.getRequestor(clientCert);
}
if (requestor == null) {
throw new OperationException(ErrorCode.NOT_PERMITTED, "no requestor specified");
}
event.addEventData(CaAuditConstants.NAME_requestor, requestor.getIdent().getName());
String respCt = null;
byte[] respBytes = null;
if (RestAPIConstants.CMD_cacert.equalsIgnoreCase(command)) {
respCt = RestAPIConstants.CT_pkix_cert;
respBytes = ca.getCaInfo().getCert().getEncodedCert();
} else if (RestAPIConstants.CMD_enroll_cert.equalsIgnoreCase(command)) {
String profile = httpRetriever.getParameter(RestAPIConstants.PARAM_profile);
if (StringUtil.isBlank(profile)) {
throw new HttpRespAuditException(HttpResponseStatus.BAD_REQUEST, null, "required parameter " + RestAPIConstants.PARAM_profile + " not specified", AuditLevel.INFO, AuditStatus.FAILED);
}
profile = profile.toLowerCase();
try {
requestor.assertPermitted(PermissionConstants.ENROLL_CERT);
} catch (InsuffientPermissionException ex) {
throw new OperationException(ErrorCode.NOT_PERMITTED, ex.getMessage());
}
if (!requestor.isCertProfilePermitted(profile)) {
throw new OperationException(ErrorCode.NOT_PERMITTED, "certProfile " + profile + " is not allowed");
}
String ct = httpRetriever.getHeader("Content-Type");
if (!RestAPIConstants.CT_pkcs10.equalsIgnoreCase(ct)) {
String message = "unsupported media type " + ct;
throw new HttpRespAuditException(HttpResponseStatus.UNSUPPORTED_MEDIA_TYPE, message, AuditLevel.INFO, AuditStatus.FAILED);
}
String strNotBefore = httpRetriever.getParameter(RestAPIConstants.PARAM_not_before);
Date notBefore = (strNotBefore == null) ? null : DateUtil.parseUtcTimeyyyyMMddhhmmss(strNotBefore);
String strNotAfter = httpRetriever.getParameter(RestAPIConstants.PARAM_not_after);
Date notAfter = (strNotAfter == null) ? null : DateUtil.parseUtcTimeyyyyMMddhhmmss(strNotAfter);
byte[] encodedCsr = request;
CertificationRequest csr = CertificationRequest.getInstance(encodedCsr);
ca.checkCsr(csr);
CertificationRequestInfo certTemp = csr.getCertificationRequestInfo();
X500Name subject = certTemp.getSubject();
SubjectPublicKeyInfo publicKeyInfo = certTemp.getSubjectPublicKeyInfo();
Extensions extensions = CaUtil.getExtensions(certTemp);
CertTemplateData certTemplate = new CertTemplateData(subject, publicKeyInfo, notBefore, notAfter, extensions, profile);
X509CertificateInfo certInfo = ca.generateCertificate(certTemplate, requestor, RequestType.REST, null, msgId);
if (ca.getCaInfo().isSaveRequest()) {
long dbId = ca.addRequest(encodedCsr);
ca.addRequestCert(dbId, certInfo.getCert().getCertId());
}
X509Cert cert = certInfo.getCert();
if (cert == null) {
String message = "could not generate certificate";
LOG.warn(message);
throw new HttpRespAuditException(HttpResponseStatus.INTERNAL_SERVER_ERROR, null, message, AuditLevel.INFO, AuditStatus.FAILED);
}
respCt = RestAPIConstants.CT_pkix_cert;
respBytes = cert.getEncodedCert();
} else if (RestAPIConstants.CMD_revoke_cert.equalsIgnoreCase(command) || RestAPIConstants.CMD_delete_cert.equalsIgnoreCase(command)) {
int permission;
if (RestAPIConstants.CMD_revoke_cert.equalsIgnoreCase(command)) {
permission = PermissionConstants.REVOKE_CERT;
} else {
permission = PermissionConstants.REMOVE_CERT;
}
try {
requestor.assertPermitted(permission);
} catch (InsuffientPermissionException ex) {
throw new OperationException(ErrorCode.NOT_PERMITTED, ex.getMessage());
}
String strCaSha1 = httpRetriever.getParameter(RestAPIConstants.PARAM_ca_sha1);
if (StringUtil.isBlank(strCaSha1)) {
throw new HttpRespAuditException(HttpResponseStatus.BAD_REQUEST, null, "required parameter " + RestAPIConstants.PARAM_ca_sha1 + " not specified", AuditLevel.INFO, AuditStatus.FAILED);
}
String strSerialNumber = httpRetriever.getParameter(RestAPIConstants.PARAM_serial_number);
if (StringUtil.isBlank(strSerialNumber)) {
throw new HttpRespAuditException(HttpResponseStatus.BAD_REQUEST, null, "required parameter " + RestAPIConstants.PARAM_serial_number + " not specified", AuditLevel.INFO, AuditStatus.FAILED);
}
if (!strCaSha1.equalsIgnoreCase(ca.getHexSha1OfCert())) {
throw new HttpRespAuditException(HttpResponseStatus.BAD_REQUEST, null, "unknown " + RestAPIConstants.PARAM_ca_sha1, AuditLevel.INFO, AuditStatus.FAILED);
}
BigInteger serialNumber = toBigInt(strSerialNumber);
if (RestAPIConstants.CMD_revoke_cert.equalsIgnoreCase(command)) {
String strReason = httpRetriever.getParameter(RestAPIConstants.PARAM_reason);
CrlReason reason = (strReason == null) ? CrlReason.UNSPECIFIED : CrlReason.forNameOrText(strReason);
if (reason == CrlReason.REMOVE_FROM_CRL) {
ca.unrevokeCertificate(serialNumber, msgId);
} else {
Date invalidityTime = null;
String strInvalidityTime = httpRetriever.getParameter(RestAPIConstants.PARAM_invalidity_time);
if (StringUtil.isNotBlank(strInvalidityTime)) {
invalidityTime = DateUtil.parseUtcTimeyyyyMMddhhmmss(strInvalidityTime);
}
ca.revokeCertificate(serialNumber, reason, invalidityTime, msgId);
}
} else if (RestAPIConstants.CMD_delete_cert.equalsIgnoreCase(command)) {
ca.removeCertificate(serialNumber, msgId);
}
} else if (RestAPIConstants.CMD_crl.equalsIgnoreCase(command)) {
try {
requestor.assertPermitted(PermissionConstants.GET_CRL);
} catch (InsuffientPermissionException ex) {
throw new OperationException(ErrorCode.NOT_PERMITTED, ex.getMessage());
}
String strCrlNumber = httpRetriever.getParameter(RestAPIConstants.PARAM_crl_number);
BigInteger crlNumber = null;
if (StringUtil.isNotBlank(strCrlNumber)) {
try {
crlNumber = toBigInt(strCrlNumber);
} catch (NumberFormatException ex) {
String message = "invalid crlNumber '" + strCrlNumber + "'";
LOG.warn(message);
throw new HttpRespAuditException(HttpResponseStatus.BAD_REQUEST, null, message, AuditLevel.INFO, AuditStatus.FAILED);
}
}
X509CRL crl = ca.getCrl(crlNumber);
if (crl == null) {
String message = "could not get CRL";
LOG.warn(message);
throw new HttpRespAuditException(HttpResponseStatus.INTERNAL_SERVER_ERROR, null, message, AuditLevel.INFO, AuditStatus.FAILED);
}
respCt = RestAPIConstants.CT_pkix_crl;
respBytes = crl.getEncoded();
} else if (RestAPIConstants.CMD_new_crl.equalsIgnoreCase(command)) {
try {
requestor.assertPermitted(PermissionConstants.GEN_CRL);
} catch (InsuffientPermissionException ex) {
throw new OperationException(ErrorCode.NOT_PERMITTED, ex.getMessage());
}
X509CRL crl = ca.generateCrlOnDemand(msgId);
if (crl == null) {
String message = "could not generate CRL";
LOG.warn(message);
throw new HttpRespAuditException(HttpResponseStatus.INTERNAL_SERVER_ERROR, null, message, AuditLevel.INFO, AuditStatus.FAILED);
}
respCt = RestAPIConstants.CT_pkix_crl;
respBytes = crl.getEncoded();
} else {
String message = "invalid command '" + command + "'";
LOG.error(message);
throw new HttpRespAuditException(HttpResponseStatus.NOT_FOUND, message, AuditLevel.INFO, AuditStatus.FAILED);
}
Map<String, String> headers = new HashMap<>();
headers.put(RestAPIConstants.HEADER_PKISTATUS, RestAPIConstants.PKISTATUS_accepted);
return new RestResponse(HttpResponseStatus.OK, respCt, headers, respBytes);
} catch (OperationException ex) {
ErrorCode code = ex.getErrorCode();
if (LOG.isWarnEnabled()) {
String msg = StringUtil.concat("generate certificate, OperationException: code=", code.name(), ", message=", ex.getErrorMessage());
LOG.warn(msg);
LOG.debug(msg, ex);
}
int sc;
String failureInfo;
switch(code) {
case ALREADY_ISSUED:
sc = HttpResponseStatus.BAD_REQUEST;
failureInfo = RestAPIConstants.FAILINFO_badRequest;
break;
case BAD_CERT_TEMPLATE:
sc = HttpResponseStatus.BAD_REQUEST;
failureInfo = RestAPIConstants.FAILINFO_badCertTemplate;
break;
case BAD_REQUEST:
sc = HttpResponseStatus.BAD_REQUEST;
failureInfo = RestAPIConstants.FAILINFO_badRequest;
break;
case CERT_REVOKED:
sc = HttpResponseStatus.CONFLICT;
failureInfo = RestAPIConstants.FAILINFO_certRevoked;
break;
case CRL_FAILURE:
sc = HttpResponseStatus.INTERNAL_SERVER_ERROR;
failureInfo = RestAPIConstants.FAILINFO_systemFailure;
break;
case DATABASE_FAILURE:
sc = HttpResponseStatus.INTERNAL_SERVER_ERROR;
failureInfo = RestAPIConstants.FAILINFO_systemFailure;
break;
case NOT_PERMITTED:
sc = HttpResponseStatus.UNAUTHORIZED;
failureInfo = RestAPIConstants.FAILINFO_notAuthorized;
break;
case INVALID_EXTENSION:
sc = HttpResponseStatus.BAD_REQUEST;
failureInfo = RestAPIConstants.FAILINFO_badRequest;
break;
case SYSTEM_FAILURE:
sc = HttpResponseStatus.INTERNAL_SERVER_ERROR;
failureInfo = RestAPIConstants.FAILINFO_systemFailure;
break;
case SYSTEM_UNAVAILABLE:
sc = HttpResponseStatus.SERVICE_UNAVAILABLE;
failureInfo = RestAPIConstants.FAILINFO_systemUnavail;
break;
case UNKNOWN_CERT:
sc = HttpResponseStatus.BAD_REQUEST;
failureInfo = RestAPIConstants.FAILINFO_badCertId;
break;
case UNKNOWN_CERT_PROFILE:
sc = HttpResponseStatus.BAD_REQUEST;
failureInfo = RestAPIConstants.FAILINFO_badCertTemplate;
break;
default:
sc = HttpResponseStatus.INTERNAL_SERVER_ERROR;
failureInfo = RestAPIConstants.FAILINFO_systemFailure;
break;
}
// end switch (code)
event.setStatus(AuditStatus.FAILED);
event.addEventData(CaAuditConstants.NAME_message, code.name());
switch(code) {
case DATABASE_FAILURE:
case SYSTEM_FAILURE:
auditMessage = code.name();
break;
default:
auditMessage = code.name() + ": " + ex.getErrorMessage();
break;
}
// end switch code
Map<String, String> headers = new HashMap<>();
headers.put(RestAPIConstants.HEADER_PKISTATUS, RestAPIConstants.PKISTATUS_rejection);
if (StringUtil.isNotBlank(failureInfo)) {
headers.put(RestAPIConstants.HEADER_failInfo, failureInfo);
}
return new RestResponse(sc, null, headers, null);
} catch (HttpRespAuditException ex) {
auditStatus = ex.getAuditStatus();
auditLevel = ex.getAuditLevel();
auditMessage = ex.getAuditMessage();
return new RestResponse(ex.getHttpStatus(), null, null, null);
} catch (Throwable th) {
if (th instanceof EOFException) {
LogUtil.warn(LOG, th, "connection reset by peer");
} else {
LOG.error("Throwable thrown, this should not happen!", th);
}
auditLevel = AuditLevel.ERROR;
auditStatus = AuditStatus.FAILED;
auditMessage = "internal error";
return new RestResponse(HttpResponseStatus.INTERNAL_SERVER_ERROR, null, null, null);
} finally {
event.setStatus(auditStatus);
event.setLevel(auditLevel);
if (auditMessage != null) {
event.addEventData(CaAuditConstants.NAME_message, auditMessage);
}
}
}
use of org.openecard.bouncycastle.asn1.x509.Extensions in project xipki by xipki.
the class IdentifiedX509Certprofile method validate.
public void validate() throws CertprofileException {
StringBuilder msg = new StringBuilder();
Map<ASN1ObjectIdentifier, ExtensionControl> controls = getExtensionControls();
// make sure that non-request extensions are not permitted in requests
Set<ASN1ObjectIdentifier> set = new HashSet<>();
for (ASN1ObjectIdentifier type : NONE_REQUEST_EXTENSION_TYPES) {
ExtensionControl control = controls.get(type);
if (control != null && control.isRequest()) {
set.add(type);
}
}
if (CollectionUtil.isNonEmpty(set)) {
msg.append("extensions ").append(toString(set)).append(" must not be contained in request, ");
}
X509CertLevel level = getCertLevel();
boolean ca = (level == X509CertLevel.RootCA) || (level == X509CertLevel.SubCA);
// make sure that CA-only extensions are not permitted in EE certificate
set.clear();
if (!ca) {
set.clear();
for (ASN1ObjectIdentifier type : CA_ONLY_EXTENSION_TYPES) {
if (controls.containsKey(type)) {
set.add(type);
}
}
if (CollectionUtil.isNonEmpty(set)) {
msg.append("EE profile contains CA-only extensions ").append(toString(set)).append(", ");
}
}
// make sure that critical only extensions are not marked as non-critical.
set.clear();
for (ASN1ObjectIdentifier type : controls.keySet()) {
ExtensionControl control = controls.get(type);
if (CRITICAL_ONLY_EXTENSION_TYPES.contains(type)) {
if (!control.isCritical()) {
set.add(type);
}
}
if (ca && CA_CRITICAL_ONLY_EXTENSION_TYPES.contains(type)) {
if (!control.isCritical()) {
set.add(type);
}
}
}
if (CollectionUtil.isNonEmpty(set)) {
msg.append("critical only extensions are marked as non-critical ");
msg.append(toString(set)).append(", ");
}
// make sure that non-critical only extensions are not marked as critical.
set.clear();
for (ASN1ObjectIdentifier type : controls.keySet()) {
ExtensionControl control = controls.get(type);
if (NONCRITICAL_ONLY_EXTENSION_TYPES.contains(type)) {
if (control.isCritical()) {
set.add(type);
}
}
}
if (CollectionUtil.isNonEmpty(set)) {
msg.append("non-critical extensions are marked as critical ").append(toString(set)).append(", ");
}
// make sure that required extensions are present
set.clear();
Set<ASN1ObjectIdentifier> requiredTypes = ca ? REQUIRED_CA_EXTENSION_TYPES : REQUIRED_EE_EXTENSION_TYPES;
for (ASN1ObjectIdentifier type : requiredTypes) {
ExtensionControl extCtrl = controls.get(type);
if (extCtrl == null || !extCtrl.isRequired()) {
set.add(type);
}
}
if (level == X509CertLevel.SubCA) {
ASN1ObjectIdentifier type = Extension.authorityKeyIdentifier;
ExtensionControl extCtrl = controls.get(type);
if (extCtrl == null || !extCtrl.isRequired()) {
set.add(type);
}
}
if (!set.isEmpty()) {
msg.append("required extensions are not marked as required ").append(toString(set)).append(", ");
}
// KeyUsage
Set<KeyUsageControl> usages = getKeyUsage();
if (ca) {
// make sure the CA certificate contains usage keyCertSign
if (!containsKeyusage(usages, KeyUsage.keyCertSign)) {
msg.append("CA profile does not contain keyUsage ").append(KeyUsage.keyCertSign).append(", ");
}
} else {
// make sure the EE certificate does not contain CA-only usages
KeyUsage[] caOnlyUsages = { KeyUsage.keyCertSign, KeyUsage.cRLSign };
Set<KeyUsage> setUsages = new HashSet<>();
for (KeyUsage caOnlyUsage : caOnlyUsages) {
if (containsKeyusage(usages, caOnlyUsage)) {
setUsages.add(caOnlyUsage);
}
}
if (CollectionUtil.isNonEmpty(set)) {
msg.append("EE profile contains CA-only keyUsage ").append(setUsages).append(", ");
}
}
final int len = msg.length();
if (len > 2) {
msg.delete(len - 2, len);
throw new CertprofileException(msg.toString());
}
}
Aggregations