use of org.bouncycastle.asn1.cmp.CertResponse in project xipki by xipki.
the class CmpCaClient method parseEnrollCertResult.
private X509Certificate parseEnrollCertResult(PKIMessage response) throws Exception {
PKIBody respBody = response.getBody();
final int bodyType = respBody.getType();
if (PKIBody.TYPE_ERROR == bodyType) {
ErrorMsgContent content = ErrorMsgContent.getInstance(respBody.getContent());
throw new Exception("Server returned PKIStatus: " + buildText(content.getPKIStatusInfo()));
} else if (PKIBody.TYPE_CERT_REP != bodyType) {
throw new Exception(String.format("unknown PKI body type %s instead the expected [%s, %s]", bodyType, PKIBody.TYPE_CERT_REP, PKIBody.TYPE_ERROR));
}
CertRepMessage certRep = CertRepMessage.getInstance(respBody.getContent());
CertResponse[] certResponses = certRep.getResponse();
if (certResponses.length != 1) {
throw new Exception("expected 1 CertResponse, but returned " + certResponses.length);
}
// We only accept the certificates which are requested.
CertResponse certResp = certResponses[0];
PKIStatusInfo statusInfo = certResp.getStatus();
int status = statusInfo.getStatus().intValue();
if (status != PKIStatus.GRANTED && status != PKIStatus.GRANTED_WITH_MODS) {
throw new Exception("Server returned PKIStatus: " + buildText(statusInfo));
}
CertifiedKeyPair cvk = certResp.getCertifiedKeyPair();
if (cvk != null) {
CMPCertificate cmpCert = cvk.getCertOrEncCert().getCertificate();
if (cmpCert != null) {
X509Certificate cert = SdkUtil.parseCert(cmpCert.getX509v3PKCert().getEncoded());
if (!verify(caCert, cert)) {
throw new Exception("The returned certificate is not issued by the given CA");
}
return cert;
}
}
throw new Exception("Server did not return any certificate");
}
use of org.bouncycastle.asn1.cmp.CertResponse in project xipki by xipki.
the class X509CaCmpResponderImpl method processP10cr.
// method processCertReqMessages
/**
* handle the PKI body with the choice {@code p10cr}<br/>
* Since it is not possible to add attribute to the PKCS#10 request (CSR), the certificate
* profile must be specified in the attribute regInfo-utf8Pairs (1.3.6.1.5.5.7.5.2.1) within
* PKIHeader.generalInfo
*/
private PKIBody processP10cr(PKIMessage request, CmpRequestorInfo requestor, ASN1OctetString tid, PKIHeader reqHeader, CertificationRequest p10cr, CmpControl cmpControl, String msgId, AuditEvent event) {
// verify the POP first
CertResponse certResp;
ASN1Integer certReqId = new ASN1Integer(-1);
boolean certGenerated = false;
X509Ca ca = getCa();
if (!securityFactory.verifyPopo(p10cr, getCmpControl().getPopoAlgoValidator())) {
LOG.warn("could not validate POP for the pkcs#10 requst");
certResp = buildErrorCertResponse(certReqId, PKIFailureInfo.badPOP, "invalid POP");
} else {
CertificationRequestInfo certTemp = p10cr.getCertificationRequestInfo();
Extensions extensions = CaUtil.getExtensions(certTemp);
X500Name subject = certTemp.getSubject();
SubjectPublicKeyInfo publicKeyInfo = certTemp.getSubjectPublicKeyInfo();
CmpUtf8Pairs keyvalues = CmpUtil.extract(reqHeader.getGeneralInfo());
String certprofileName = null;
Date notBefore = null;
Date notAfter = null;
if (keyvalues != null) {
certprofileName = keyvalues.value(CmpUtf8Pairs.KEY_CERTPROFILE);
String str = keyvalues.value(CmpUtf8Pairs.KEY_NOTBEFORE);
if (str != null) {
notBefore = DateUtil.parseUtcTimeyyyyMMddhhmmss(str);
}
str = keyvalues.value(CmpUtf8Pairs.KEY_NOTAFTER);
if (str != null) {
notAfter = DateUtil.parseUtcTimeyyyyMMddhhmmss(str);
}
}
if (certprofileName == null) {
certResp = buildErrorCertResponse(certReqId, PKIFailureInfo.badCertTemplate, "badCertTemplate", null);
} else {
certprofileName = certprofileName.toLowerCase();
if (!requestor.isCertProfilePermitted(certprofileName)) {
String msg = "certprofile " + certprofileName + " is not allowed";
certResp = buildErrorCertResponse(certReqId, PKIFailureInfo.notAuthorized, msg);
} else {
CertTemplateData certTemplateData = new CertTemplateData(subject, publicKeyInfo, notBefore, notAfter, extensions, certprofileName);
certResp = generateCertificates(Arrays.asList(certTemplateData), Arrays.asList(certReqId), requestor, tid, false, request, cmpControl, msgId, event).get(0);
certGenerated = true;
}
}
}
CMPCertificate[] caPubs = null;
if (certGenerated && cmpControl.isSendCaCert()) {
caPubs = new CMPCertificate[] { ca.getCaInfo().getCertInCmpFormat() };
}
CertRepMessage repMessage = new CertRepMessage(caPubs, new CertResponse[] { certResp });
return new PKIBody(PKIBody.TYPE_CERT_REP, repMessage);
}
use of org.bouncycastle.asn1.cmp.CertResponse in project xipki by xipki.
the class X509CaCmpResponderImpl method processCertReqMessages.
private CertRepMessage processCertReqMessages(PKIMessage request, CmpRequestorInfo requestor, ASN1OctetString tid, PKIHeader reqHeader, CertReqMessages kur, boolean keyUpdate, CmpControl cmpControl, String msgId, AuditEvent event) {
CmpRequestorInfo tmpRequestor = (CmpRequestorInfo) requestor;
CertReqMsg[] certReqMsgs = kur.toCertReqMsgArray();
final int n = certReqMsgs.length;
Map<Integer, CertTemplateData> certTemplateDatas = new HashMap<>(n * 10 / 6);
Map<Integer, CertResponse> certResponses = new HashMap<>(n * 10 / 6);
Map<Integer, ASN1Integer> certReqIds = new HashMap<>(n * 10 / 6);
// pre-process requests
for (int i = 0; i < n; i++) {
if (cmpControl.isGroupEnroll() && certTemplateDatas.size() != i) {
// last certReqMsg cannot be used to enroll certificate
break;
}
CertReqMsg reqMsg = certReqMsgs[i];
CertificateRequestMessage req = new CertificateRequestMessage(reqMsg);
ASN1Integer certReqId = reqMsg.getCertReq().getCertReqId();
certReqIds.put(i, certReqId);
if (!req.hasProofOfPossession()) {
certResponses.put(i, buildErrorCertResponse(certReqId, PKIFailureInfo.badPOP, "no POP", null));
continue;
}
if (!verifyPopo(req, tmpRequestor.isRa())) {
LOG.warn("could not validate POP for request {}", certReqId.getValue());
certResponses.put(i, buildErrorCertResponse(certReqId, PKIFailureInfo.badPOP, "invalid POP", null));
continue;
}
CmpUtf8Pairs keyvalues = CmpUtil.extract(reqMsg.getRegInfo());
String certprofileName = (keyvalues == null) ? null : keyvalues.value(CmpUtf8Pairs.KEY_CERTPROFILE);
if (certprofileName == null) {
String msg = "no certificate profile";
certResponses.put(i, buildErrorCertResponse(certReqId, PKIFailureInfo.badCertTemplate, msg));
continue;
}
certprofileName = certprofileName.toLowerCase();
if (!tmpRequestor.isCertProfilePermitted(certprofileName)) {
String msg = "certprofile " + certprofileName + " is not allowed";
certResponses.put(i, buildErrorCertResponse(certReqId, PKIFailureInfo.notAuthorized, msg));
continue;
}
CertTemplate certTemp = req.getCertTemplate();
OptionalValidity validity = certTemp.getValidity();
Date notBefore = null;
Date notAfter = null;
if (validity != null) {
Time time = validity.getNotBefore();
if (time != null) {
notBefore = time.getDate();
}
time = validity.getNotAfter();
if (time != null) {
notAfter = time.getDate();
}
}
CertTemplateData certTempData = new CertTemplateData(certTemp.getSubject(), certTemp.getPublicKey(), notBefore, notAfter, certTemp.getExtensions(), certprofileName);
certTemplateDatas.put(i, certTempData);
}
if (certResponses.size() == n) {
// all error
CertResponse[] certResps = new CertResponse[n];
for (int i = 0; i < n; i++) {
certResps[i] = certResponses.get(i);
}
return new CertRepMessage(null, certResps);
}
if (cmpControl.isGroupEnroll() && certTemplateDatas.size() != n) {
// at least one certRequest cannot be used to enroll certificate
int lastFailureIndex = certTemplateDatas.size();
BigInteger failCertReqId = certReqIds.get(lastFailureIndex).getPositiveValue();
CertResponse failCertResp = certResponses.get(lastFailureIndex);
PKIStatus failStatus = PKIStatus.getInstance(new ASN1Integer(failCertResp.getStatus().getStatus()));
PKIFailureInfo failureInfo = new PKIFailureInfo(failCertResp.getStatus().getFailInfo());
CertResponse[] certResps = new CertResponse[n];
for (int i = 0; i < n; i++) {
if (i == lastFailureIndex) {
certResps[i] = failCertResp;
continue;
}
ASN1Integer certReqId = certReqIds.get(i);
String msg = "error in certReq " + failCertReqId;
PKIStatusInfo tmpStatus = generateRejectionStatus(failStatus, failureInfo.intValue(), msg);
certResps[i] = new CertResponse(certReqId, tmpStatus);
}
return new CertRepMessage(null, certResps);
}
final int k = certTemplateDatas.size();
List<CertTemplateData> certTemplateList = new ArrayList<>(k);
List<ASN1Integer> certReqIdList = new ArrayList<>(k);
Map<Integer, Integer> reqIndexToCertIndexMap = new HashMap<>(k * 10 / 6);
for (int i = 0; i < n; i++) {
if (!certTemplateDatas.containsKey(i)) {
continue;
}
certTemplateList.add(certTemplateDatas.get(i));
certReqIdList.add(certReqIds.get(i));
reqIndexToCertIndexMap.put(i, certTemplateList.size() - 1);
}
List<CertResponse> generateCertResponses = generateCertificates(certTemplateList, certReqIdList, tmpRequestor, tid, keyUpdate, request, cmpControl, msgId, event);
boolean anyCertEnrolled = false;
CertResponse[] certResps = new CertResponse[n];
for (int i = 0; i < n; i++) {
if (certResponses.containsKey(i)) {
certResps[i] = certResponses.get(i);
} else {
int respIndex = reqIndexToCertIndexMap.get(i);
certResps[i] = generateCertResponses.get(respIndex);
if (!anyCertEnrolled && certResps[i].getCertifiedKeyPair() != null) {
anyCertEnrolled = true;
}
}
}
CMPCertificate[] caPubs = null;
if (anyCertEnrolled && cmpControl.isSendCaCert()) {
caPubs = new CMPCertificate[] { getCa().getCaInfo().getCertInCmpFormat() };
}
return new CertRepMessage(caPubs, certResps);
}
use of org.bouncycastle.asn1.cmp.CertResponse in project xipki by xipki.
the class X509CmpRequestor method requestCertificate0.
private EnrollCertResultResp requestCertificate0(PKIMessage reqMessage, Map<BigInteger, String> reqIdIdMap, int expectedBodyType, RequestResponseDebug debug) throws CmpRequestorException, PkiErrorException {
PkiResponse response = signAndSend(reqMessage, debug);
checkProtection(response);
PKIBody respBody = response.getPkiMessage().getBody();
final int bodyType = respBody.getType();
if (PKIBody.TYPE_ERROR == bodyType) {
ErrorMsgContent content = ErrorMsgContent.getInstance(respBody.getContent());
throw new PkiErrorException(content.getPKIStatusInfo());
} else if (expectedBodyType != bodyType) {
throw new CmpRequestorException(String.format("unknown PKI body type %s instead the expected [%s, %s]", bodyType, expectedBodyType, PKIBody.TYPE_ERROR));
}
CertRepMessage certRep = CertRepMessage.getInstance(respBody.getContent());
CertResponse[] certResponses = certRep.getResponse();
EnrollCertResultResp result = new EnrollCertResultResp();
// CA certificates
CMPCertificate[] caPubs = certRep.getCaPubs();
if (caPubs != null && caPubs.length > 0) {
for (int i = 0; i < caPubs.length; i++) {
if (caPubs[i] != null) {
result.addCaCertificate(caPubs[i]);
}
}
}
CertificateConfirmationContentBuilder certConfirmBuilder = null;
if (!CmpUtil.isImplictConfirm(response.getPkiMessage().getHeader())) {
certConfirmBuilder = new CertificateConfirmationContentBuilder();
}
boolean requireConfirm = false;
// We only accept the certificates which are requested.
for (CertResponse certResp : certResponses) {
PKIStatusInfo statusInfo = certResp.getStatus();
int status = statusInfo.getStatus().intValue();
BigInteger certReqId = certResp.getCertReqId().getValue();
String thisId = reqIdIdMap.get(certReqId);
if (thisId != null) {
reqIdIdMap.remove(certReqId);
} else if (reqIdIdMap.size() == 1) {
thisId = reqIdIdMap.values().iterator().next();
reqIdIdMap.clear();
}
if (thisId == null) {
// ignore it. this cert is not requested by me
continue;
}
ResultEntry resultEntry;
if (status == PKIStatus.GRANTED || status == PKIStatus.GRANTED_WITH_MODS) {
CertifiedKeyPair cvk = certResp.getCertifiedKeyPair();
if (cvk == null) {
return null;
}
CMPCertificate cmpCert = cvk.getCertOrEncCert().getCertificate();
if (cmpCert == null) {
return null;
}
resultEntry = new EnrollCertResultEntry(thisId, cmpCert, status);
if (certConfirmBuilder != null) {
requireConfirm = true;
X509CertificateHolder certHolder = null;
try {
certHolder = new X509CertificateHolder(cmpCert.getEncoded());
} catch (IOException ex) {
resultEntry = new ErrorResultEntry(thisId, ClientErrorCode.PKISTATUS_RESPONSE_ERROR, PKIFailureInfo.systemFailure, "could not decode the certificate");
}
if (certHolder != null) {
certConfirmBuilder.addAcceptedCertificate(certHolder, certReqId);
}
}
} else {
PKIFreeText statusString = statusInfo.getStatusString();
String errorMessage = (statusString == null) ? null : statusString.getStringAt(0).getString();
int failureInfo = statusInfo.getFailInfo().intValue();
resultEntry = new ErrorResultEntry(thisId, status, failureInfo, errorMessage);
}
result.addResultEntry(resultEntry);
}
if (CollectionUtil.isNonEmpty(reqIdIdMap)) {
for (BigInteger reqId : reqIdIdMap.keySet()) {
ErrorResultEntry ere = new ErrorResultEntry(reqIdIdMap.get(reqId), ClientErrorCode.PKISTATUS_NO_ANSWER);
result.addResultEntry(ere);
}
}
if (!requireConfirm) {
return result;
}
PKIMessage confirmRequest = buildCertConfirmRequest(response.getPkiMessage().getHeader().getTransactionID(), certConfirmBuilder);
response = signAndSend(confirmRequest, debug);
checkProtection(response);
return result;
}
use of org.bouncycastle.asn1.cmp.CertResponse in project xipki by xipki.
the class X509CaCmpResponderImpl method postProcessCertInfo.
// method generateCertificates
private CertResponse postProcessCertInfo(ASN1Integer certReqId, X509CertificateInfo certInfo, ASN1OctetString tid, CmpControl cmpControl) {
if (cmpControl.isConfirmCert()) {
pendingCertPool.addCertificate(tid.getOctets(), certReqId.getPositiveValue(), certInfo, System.currentTimeMillis() + cmpControl.getConfirmWaitTimeMs());
}
String warningMsg = certInfo.getWarningMessage();
PKIStatusInfo statusInfo;
if (StringUtil.isBlank(warningMsg)) {
statusInfo = certInfo.isAlreadyIssued() ? new PKIStatusInfo(PKIStatus.grantedWithMods, new PKIFreeText("ALREADY_ISSUED")) : new PKIStatusInfo(PKIStatus.granted);
} else {
statusInfo = new PKIStatusInfo(PKIStatus.grantedWithMods, new PKIFreeText(warningMsg));
}
CertOrEncCert cec = new CertOrEncCert(CMPCertificate.getInstance(certInfo.getCert().getEncodedCert()));
CertifiedKeyPair kp = new CertifiedKeyPair(cec);
return new CertResponse(certReqId, statusInfo, kp, null);
}
Aggregations