use of com.github.zhenwei.pkix.util.asn1.cmp.PKIStatusInfo in project gdmatrix by gdmatrix.
the class CMSUtils method sendData.
private static TimeStampResp sendData(InputStream dataToBeSent, String serviceURI) throws Exception {
URL url = new URL(serviceURI);
URLConnection conn = url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
// post request data
OutputStream os = conn.getOutputStream();
byte[] buffer = new byte[4096];
int numRead = dataToBeSent.read(buffer);
while (numRead > 0) {
os.write(buffer, 0, numRead);
numRead = dataToBeSent.read(buffer);
}
os.flush();
// read response
InputStream response = conn.getInputStream();
ASN1InputStream asn1Is = new ASN1InputStream(response);
// TimeStampResp tspResp = new TimeStampResp((ASN1Sequence)asn1Is.readObject());
Enumeration e = ((ASN1Sequence) asn1Is.readObject()).getObjects();
PKIStatusInfo pkiStatusInfo = PKIStatusInfo.getInstance(e.nextElement());
ContentInfo timeStampToken = null;
if (e.hasMoreElements()) {
timeStampToken = ContentInfo.getInstance(e.nextElement());
}
TimeStampResp tspResp = new TimeStampResp(pkiStatusInfo, timeStampToken);
return tspResp;
}
use of com.github.zhenwei.pkix.util.asn1.cmp.PKIStatusInfo in project ca3sCore by kuehne-trustable-de.
the class CaCmpConnector method readCertResponse.
/**
* @param responseBytes
* @param pkiMessageReq
* @param csr
* @param config
* @throws IOException
* @throws CRMFException
* @throws CMPException
* @throws GeneralSecurityException
*/
public de.trustable.ca3s.core.domain.Certificate readCertResponse(final byte[] responseBytes, final PKIMessage pkiMessageReq, final CSR csr, final CAConnectorConfig config) throws IOException, CRMFException, CMPException, GeneralSecurityException {
final ASN1Primitive derObject = cryptoUtil.getDERObject(responseBytes);
final PKIMessage pkiMessage = PKIMessage.getInstance(derObject);
if (pkiMessage == null) {
throw new GeneralSecurityException("No CMP message could be parsed from received Der object.");
}
printPKIMessageInfo(pkiMessage);
PKIHeader pkiHeaderReq = pkiMessageReq.getHeader();
PKIHeader pkiHeaderResp = pkiMessage.getHeader();
if (!pkiHeaderReq.getSenderNonce().equals(pkiHeaderResp.getRecipNonce())) {
ASN1OctetString asn1Oct = pkiHeaderResp.getRecipNonce();
if (asn1Oct == null) {
LOGGER.info("Recip nonce == null");
} else {
LOGGER.info("sender nonce " + java.util.Base64.getEncoder().encodeToString(pkiHeaderReq.getSenderNonce().getOctets()) + " != " + java.util.Base64.getEncoder().encodeToString(asn1Oct.getOctets()));
}
throw new GeneralSecurityException("Sender / Recip nonce mismatch");
}
if (!pkiHeaderReq.getTransactionID().equals(pkiHeaderResp.getTransactionID())) {
ASN1OctetString asn1Oct = pkiHeaderResp.getTransactionID();
if (asn1Oct == null) {
LOGGER.info("transaction id == null");
} else {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("transaction id " + java.util.Base64.getEncoder().encodeToString(pkiHeaderReq.getTransactionID().getOctets()) + " != " + java.util.Base64.getEncoder().encodeToString(asn1Oct.getOctets()));
}
}
throw new GeneralSecurityException("Sender / Recip Transaction Id mismatch");
}
final PKIBody body = pkiMessage.getBody();
int tagno = body.getType();
if (tagno == PKIBody.TYPE_ERROR) {
handleCMPError(body);
} else if (tagno == PKIBody.TYPE_CERT_REP || tagno == PKIBody.TYPE_INIT_REP) {
// certificate successfully generated
CertRepMessage certRepMessage = CertRepMessage.getInstance(body.getContent());
try {
// CMPCertificate[] cmpCertArr = certRepMessage.getCaPubs();
CMPCertificate[] cmpCertArr = pkiMessage.getExtraCerts();
LOGGER.info("CMP Response body contains " + cmpCertArr.length + " extra certificates");
for (int i = 0; i < cmpCertArr.length; i++) {
CMPCertificate cmpCert = cmpCertArr[i];
LOGGER.info("Added CA '" + cmpCert.getX509v3PKCert().getSubject() + "' from CMP Response body");
de.trustable.ca3s.core.domain.Certificate certDao = certUtil.createCertificate(cmpCert.getEncoded(), null, null, true);
certificateRepository.save(certDao);
LOGGER.debug("Additional CA '" + certDao.getSubject() + "' from CMP Response body");
}
} catch (NullPointerException npe) {
// NOSONAR
// just ignore
}
CertResponse[] respArr = certRepMessage.getResponse();
if (respArr == null || (respArr.length == 0)) {
throw new GeneralSecurityException("No CMP response found.");
}
LOGGER.info("CMP Response body contains " + respArr.length + " elements");
for (int i = 0; i < respArr.length; i++) {
if (respArr[i] == null) {
throw new GeneralSecurityException("No CMP response returned.");
}
BigInteger status = BigInteger.ZERO;
String statusText = "";
PKIStatusInfo pkiStatusInfo = respArr[i].getStatus();
if (pkiStatusInfo != null) {
PKIFreeText freeText = pkiStatusInfo.getStatusString();
if (freeText != null) {
for (int j = 0; j < freeText.size(); j++) {
statusText = freeText.getStringAt(j) + "\n";
}
}
}
if ((respArr[i].getCertifiedKeyPair() == null) || (respArr[i].getCertifiedKeyPair().getCertOrEncCert() == null)) {
csrUtil.setStatus(csr, CsrStatus.REJECTED);
csrUtil.setCsrAttribute(csr, CsrAttribute.ATTRIBUTE_FAILURE_INFO, statusText, true);
throw new GeneralSecurityException("CMP response contains no certificate, status :" + status + "\n" + statusText);
}
CMPCertificate cmpCert = respArr[i].getCertifiedKeyPair().getCertOrEncCert().getCertificate();
if (cmpCert != null) {
org.bouncycastle.asn1.x509.Certificate cmpCertificate = cmpCert.getX509v3PKCert();
if (cmpCertificate != null) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("#" + i + ": " + cmpCertificate);
}
final CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC");
/*
* version returning just the end entity ...
*/
final Collection<? extends java.security.cert.Certificate> certificateChain = certificateFactory.generateCertificates(new ByteArrayInputStream(cmpCertificate.getEncoded()));
X509Certificate[] certArray = certificateChain.toArray(new X509Certificate[0]);
X509Certificate cert = certArray[0];
if (LOGGER.isDebugEnabled()) {
LOGGER.info("#" + i + ": " + cert);
}
de.trustable.ca3s.core.domain.Certificate certDao = certUtil.createCertificate(cert.getEncoded(), csr, null, false);
certDao.setRevocationCA(config);
certificateRepository.save(certDao);
return certDao;
}
}
}
} else {
throw new GeneralSecurityException("unexpected PKI body type :" + tagno);
}
return null;
}
use of com.github.zhenwei.pkix.util.asn1.cmp.PKIStatusInfo 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 com.github.zhenwei.pkix.util.asn1.cmp.PKIStatusInfo in project xipki by xipki.
the class CmpResponder method buildErrorPkiMessage.
// method addProtection
protected PKIMessage buildErrorPkiMessage(ASN1OctetString tid, PKIHeader requestHeader, int failureCode, String statusText) {
GeneralName respRecipient = requestHeader.getSender();
PKIHeaderBuilder respHeader = new PKIHeaderBuilder(requestHeader.getPvno().getValue().intValue(), getSender(), respRecipient);
respHeader.setMessageTime(new ASN1GeneralizedTime(new Date()));
if (tid != null) {
respHeader.setTransactionID(tid);
}
ASN1OctetString senderNonce = requestHeader.getSenderNonce();
if (senderNonce != null) {
respHeader.setRecipNonce(senderNonce);
}
PKIStatusInfo status = generateRejectionStatus(failureCode, statusText);
ErrorMsgContent error = new ErrorMsgContent(status);
PKIBody body = new PKIBody(PKIBody.TYPE_ERROR, error);
return new PKIMessage(respHeader.build(), body);
}
use of com.github.zhenwei.pkix.util.asn1.cmp.PKIStatusInfo in project xipki by xipki.
the class X509CaCmpResponderImpl method cmpUnRevokeRemoveCertificates.
// method cmpEnrollCert
private PKIBody cmpUnRevokeRemoveCertificates(PKIMessage request, PKIHeaderBuilder respHeader, CmpControl cmpControl, PKIHeader reqHeader, PKIBody reqBody, CmpRequestorInfo requestor, String msgId, AuditEvent event) {
Integer requiredPermission = null;
boolean allRevdetailsOfSameType = true;
RevReqContent rr = RevReqContent.getInstance(reqBody.getContent());
RevDetails[] revContent = rr.toRevDetailsArray();
int len = revContent.length;
for (int i = 0; i < len; i++) {
RevDetails revDetails = revContent[i];
Extensions crlDetails = revDetails.getCrlEntryDetails();
int reasonCode = CrlReason.UNSPECIFIED.getCode();
if (crlDetails != null) {
ASN1ObjectIdentifier extId = Extension.reasonCode;
ASN1Encodable extValue = crlDetails.getExtensionParsedValue(extId);
if (extValue != null) {
reasonCode = ASN1Enumerated.getInstance(extValue).getValue().intValue();
}
}
if (reasonCode == XiSecurityConstants.CMP_CRL_REASON_REMOVE) {
if (requiredPermission == null) {
event.addEventType(CaAuditConstants.TYPE_CMP_rr_remove);
requiredPermission = PermissionConstants.REMOVE_CERT;
} else if (requiredPermission != PermissionConstants.REMOVE_CERT) {
allRevdetailsOfSameType = false;
break;
}
} else if (reasonCode == CrlReason.REMOVE_FROM_CRL.getCode()) {
if (requiredPermission == null) {
event.addEventType(CaAuditConstants.TYPE_CMP_rr_unrevoke);
requiredPermission = PermissionConstants.UNREVOKE_CERT;
} else if (requiredPermission != PermissionConstants.UNREVOKE_CERT) {
allRevdetailsOfSameType = false;
break;
}
} else {
if (requiredPermission == null) {
event.addEventType(CaAuditConstants.TYPE_CMP_rr_revoke);
requiredPermission = PermissionConstants.REVOKE_CERT;
} else if (requiredPermission != PermissionConstants.REVOKE_CERT) {
allRevdetailsOfSameType = false;
break;
}
}
}
if (!allRevdetailsOfSameType) {
ErrorMsgContent emc = new ErrorMsgContent(new PKIStatusInfo(PKIStatus.rejection, new PKIFreeText("not all revDetails are of the same type"), new PKIFailureInfo(PKIFailureInfo.badRequest)));
return new PKIBody(PKIBody.TYPE_ERROR, emc);
} else {
try {
checkPermission(requestor, requiredPermission);
} catch (InsuffientPermissionException ex) {
event.setStatus(AuditStatus.FAILED);
event.addEventData(CaAuditConstants.NAME_message, "NOT_PERMITTED");
return buildErrorMsgPkiBody(PKIStatus.rejection, PKIFailureInfo.notAuthorized, null);
}
return unRevokeRemoveCertificates(request, rr, requiredPermission, cmpControl, msgId);
}
}
Aggregations