use of org.gudy.bouncycastle.asn1.cms.ContentInfo in project xipki by xipki.
the class HttpScepServlet method service0.
private void service0(HttpServletRequest req, HttpServletResponse resp, boolean viaPost) throws ServletException, IOException {
AuditServiceRegister auditServiceRegister = ServletHelper.getAuditServiceRegister();
if (auditServiceRegister == null) {
LOG.error("ServletHelper.auditServiceRegister not configured");
sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
ResponderManager responderManager = ServletHelper.getResponderManager();
if (responderManager == null) {
LOG.error("ServletHelper.responderManager not configured");
sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
String path = StringUtil.getRelativeRequestUri(req.getServletPath(), req.getRequestURI());
String scepName = null;
String certProfileName = null;
if (path.length() > 1) {
String scepPath = path;
if (scepPath.endsWith(CGI_PROGRAM)) {
// skip also the first char (which is always '/')
String tpath = scepPath.substring(1, scepPath.length() - CGI_PROGRAM_LEN);
String[] tokens = tpath.split("/");
if (tokens.length == 2) {
scepName = tokens[0];
certProfileName = tokens[1].toLowerCase();
}
}
// end if
}
if (scepName == null || certProfileName == null) {
sendError(resp, HttpServletResponse.SC_NOT_FOUND);
return;
}
AuditService auditService = auditServiceRegister.getAuditService();
AuditEvent event = new AuditEvent(new Date());
event.setApplicationName("SCEP");
event.setName(CaAuditConstants.NAME_PERF);
event.addEventData(CaAuditConstants.NAME_SCEP_name, scepName + "/" + certProfileName);
event.addEventData(CaAuditConstants.NAME_reqType, RequestType.SCEP.name());
String msgId = RandomUtil.nextHexLong();
event.addEventData(CaAuditConstants.NAME_mid, msgId);
AuditLevel auditLevel = AuditLevel.INFO;
AuditStatus auditStatus = AuditStatus.SUCCESSFUL;
String auditMessage = null;
try {
Scep responder = responderManager.getScep(scepName);
if (responder == null || !responder.isOnService() || !responder.supportsCertProfile(certProfileName)) {
auditMessage = "unknown SCEP '" + scepName + "/" + certProfileName + "'";
LOG.warn(auditMessage);
auditStatus = AuditStatus.FAILED;
sendError(resp, HttpServletResponse.SC_NOT_FOUND);
return;
}
String operation = req.getParameter("operation");
event.addEventData(CaAuditConstants.NAME_SCEP_operation, operation);
if ("PKIOperation".equalsIgnoreCase(operation)) {
CMSSignedData reqMessage;
// parse the request
try {
byte[] content;
if (viaPost) {
content = IoUtil.read(req.getInputStream());
} else {
String b64 = req.getParameter("message");
content = Base64.decode(b64);
}
reqMessage = new CMSSignedData(content);
} catch (Exception ex) {
final String msg = "invalid request";
LogUtil.error(LOG, ex, msg);
auditMessage = msg;
auditStatus = AuditStatus.FAILED;
sendError(resp, HttpServletResponse.SC_BAD_REQUEST);
return;
}
ContentInfo ci;
try {
ci = responder.servicePkiOperation(reqMessage, certProfileName, msgId, event);
} catch (MessageDecodingException ex) {
final String msg = "could not decrypt and/or verify the request";
LogUtil.error(LOG, ex, msg);
auditMessage = msg;
auditStatus = AuditStatus.FAILED;
sendError(resp, HttpServletResponse.SC_BAD_REQUEST);
return;
} catch (OperationException ex) {
ErrorCode code = ex.getErrorCode();
int httpCode;
switch(code) {
case ALREADY_ISSUED:
case CERT_REVOKED:
case CERT_UNREVOKED:
httpCode = HttpServletResponse.SC_FORBIDDEN;
break;
case BAD_CERT_TEMPLATE:
case BAD_REQUEST:
case BAD_POP:
case INVALID_EXTENSION:
case UNKNOWN_CERT:
case UNKNOWN_CERT_PROFILE:
httpCode = HttpServletResponse.SC_BAD_REQUEST;
break;
case NOT_PERMITTED:
httpCode = HttpServletResponse.SC_UNAUTHORIZED;
break;
case SYSTEM_UNAVAILABLE:
httpCode = HttpServletResponse.SC_SERVICE_UNAVAILABLE;
break;
case CRL_FAILURE:
case DATABASE_FAILURE:
case SYSTEM_FAILURE:
httpCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
break;
default:
httpCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
break;
}
auditMessage = ex.getMessage();
LogUtil.error(LOG, ex, auditMessage);
auditStatus = AuditStatus.FAILED;
sendError(resp, httpCode);
return;
}
byte[] bodyBytes = ci.getEncoded();
sendOKResponse(resp, CT_RESPONSE, bodyBytes);
} else if (Operation.GetCACaps.getCode().equalsIgnoreCase(operation)) {
// CA-Ident is ignored
byte[] caCapsBytes = responder.getCaCaps().getBytes();
sendOKResponse(resp, ScepConstants.CT_TEXT_PLAIN, caCapsBytes);
} else if (Operation.GetCACert.getCode().equalsIgnoreCase(operation)) {
// CA-Ident is ignored
byte[] respBytes = responder.getCaCertResp().getBytes();
sendOKResponse(resp, ScepConstants.CT_X509_CA_RA_CERT, respBytes);
} else if (Operation.GetNextCACert.getCode().equalsIgnoreCase(operation)) {
auditMessage = "SCEP operation '" + operation + "' is not permitted";
auditStatus = AuditStatus.FAILED;
sendError(resp, HttpServletResponse.SC_FORBIDDEN);
return;
} else {
auditMessage = "unknown SCEP operation '" + operation + "'";
auditStatus = AuditStatus.FAILED;
sendError(resp, HttpServletResponse.SC_BAD_REQUEST);
return;
}
} catch (Throwable th) {
if (th instanceof EOFException) {
final String msg = "connection reset by peer";
if (LOG.isWarnEnabled()) {
LogUtil.warn(LOG, th, msg);
}
LOG.debug(msg, th);
} else {
LOG.error("Throwable thrown, this should not happen!", th);
}
auditLevel = AuditLevel.ERROR;
auditStatus = AuditStatus.FAILED;
auditMessage = "internal error";
sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
} finally {
audit(auditService, event, auditLevel, auditStatus, auditMessage);
}
}
use of org.gudy.bouncycastle.asn1.cms.ContentInfo in project xipki by xipki.
the class ScepImpl method servicePkiOperation0.
// method servicePkiOperation
private PkiMessage servicePkiOperation0(CMSSignedData requestContent, DecodedPkiMessage req, String certProfileName, String msgId, AuditEvent event) throws MessageDecodingException, OperationException {
ParamUtil.requireNonNull("requestContent", requestContent);
ParamUtil.requireNonNull("req", req);
String tid = req.getTransactionId().getId();
// verify and decrypt the request
audit(event, CaAuditConstants.NAME_tid, tid);
if (req.getFailureMessage() != null) {
audit(event, CaAuditConstants.NAME_SCEP_failureMessage, req.getFailureMessage());
}
Boolean bo = req.isSignatureValid();
if (bo != null && !bo.booleanValue()) {
audit(event, CaAuditConstants.NAME_SCEP_signature, "invalid");
}
bo = req.isDecryptionSuccessful();
if (bo != null && !bo.booleanValue()) {
audit(event, CaAuditConstants.NAME_SCEP_decryption, "failed");
}
PkiMessage rep = new PkiMessage(req.getTransactionId(), MessageType.CertRep, Nonce.randomNonce());
rep.setRecipientNonce(req.getSenderNonce());
if (req.getFailureMessage() != null) {
rep.setPkiStatus(PkiStatus.FAILURE);
rep.setFailInfo(FailInfo.badRequest);
return rep;
}
bo = req.isSignatureValid();
if (bo != null && !bo.booleanValue()) {
rep.setPkiStatus(PkiStatus.FAILURE);
rep.setFailInfo(FailInfo.badMessageCheck);
return rep;
}
bo = req.isDecryptionSuccessful();
if (bo != null && !bo.booleanValue()) {
rep.setPkiStatus(PkiStatus.FAILURE);
rep.setFailInfo(FailInfo.badRequest);
return rep;
}
Date signingTime = req.getSigningTime();
if (maxSigningTimeBiasInMs > 0) {
boolean isTimeBad = false;
if (signingTime == null) {
isTimeBad = true;
} else {
long now = System.currentTimeMillis();
long diff = now - signingTime.getTime();
if (diff < 0) {
diff = -1 * diff;
}
isTimeBad = diff > maxSigningTimeBiasInMs;
}
if (isTimeBad) {
rep.setPkiStatus(PkiStatus.FAILURE);
rep.setFailInfo(FailInfo.badTime);
return rep;
}
}
// end if
// check the digest algorithm
String oid = req.getDigestAlgorithm().getId();
ScepHashAlgo hashAlgo = ScepHashAlgo.forNameOrOid(oid);
if (hashAlgo == null) {
LOG.warn("tid={}: unknown digest algorithm {}", tid, oid);
rep.setPkiStatus(PkiStatus.FAILURE);
rep.setFailInfo(FailInfo.badAlg);
return rep;
}
boolean supported = false;
if (hashAlgo == ScepHashAlgo.SHA1) {
if (caCaps.containsCapability(CaCapability.SHA1)) {
supported = true;
}
} else if (hashAlgo == ScepHashAlgo.SHA256) {
if (caCaps.containsCapability(CaCapability.SHA256)) {
supported = true;
}
} else if (hashAlgo == ScepHashAlgo.SHA512) {
if (caCaps.containsCapability(CaCapability.SHA512)) {
supported = true;
}
}
if (!supported) {
LOG.warn("tid={}: unsupported digest algorithm {}", tid, oid);
rep.setPkiStatus(PkiStatus.FAILURE);
rep.setFailInfo(FailInfo.badAlg);
return rep;
}
// check the content encryption algorithm
ASN1ObjectIdentifier encOid = req.getContentEncryptionAlgorithm();
if (CMSAlgorithm.DES_EDE3_CBC.equals(encOid)) {
if (!caCaps.containsCapability(CaCapability.DES3)) {
LOG.warn("tid={}: encryption with DES3 algorithm is not permitted", tid, encOid);
rep.setPkiStatus(PkiStatus.FAILURE);
rep.setFailInfo(FailInfo.badAlg);
return rep;
}
} else if (AES_ENC_ALGOS.contains(encOid)) {
if (!caCaps.containsCapability(CaCapability.AES)) {
LOG.warn("tid={}: encryption with AES algorithm {} is not permitted", tid, encOid);
rep.setPkiStatus(PkiStatus.FAILURE);
rep.setFailInfo(FailInfo.badAlg);
return rep;
}
} else {
LOG.warn("tid={}: encryption with algorithm {} is not permitted", tid, encOid);
rep.setPkiStatus(PkiStatus.FAILURE);
rep.setFailInfo(FailInfo.badAlg);
return rep;
}
X509Ca ca;
try {
ca = caManager.getX509Ca(caIdent);
} catch (CaMgmtException ex) {
LogUtil.error(LOG, ex, tid + "=" + tid + ",could not get X509CA");
throw new OperationException(ErrorCode.SYSTEM_FAILURE, ex);
}
X500Name caX500Name = ca.getCaInfo().getCert().getSubjectAsX500Name();
try {
SignedData signedData;
MessageType mt = req.getMessageType();
audit(event, CaAuditConstants.NAME_SCEP_messageType, mt.toString());
switch(mt) {
case PKCSReq:
case RenewalReq:
case UpdateReq:
CertificationRequest csr = CertificationRequest.getInstance(req.getMessageData());
X500Name reqSubject = csr.getCertificationRequestInfo().getSubject();
if (LOG.isInfoEnabled()) {
LOG.info("tid={}, subject={}", tid, X509Util.getRfc4519Name(reqSubject));
}
try {
ca.checkCsr(csr);
} catch (OperationException ex) {
LogUtil.warn(LOG, ex, "tid=" + tid + " POPO verification failed");
throw FailInfoException.BAD_MESSAGE_CHECK;
}
CertificationRequestInfo csrReqInfo = csr.getCertificationRequestInfo();
X509Certificate reqSignatureCert = req.getSignatureCert();
X500Principal reqSigCertSubject = reqSignatureCert.getSubjectX500Principal();
boolean selfSigned = reqSigCertSubject.equals(reqSignatureCert.getIssuerX500Principal());
if (selfSigned) {
X500Name tmp = X500Name.getInstance(reqSigCertSubject.getEncoded());
if (!tmp.equals(csrReqInfo.getSubject())) {
LOG.warn("tid={}, self-signed identityCert.subject != csr.subject");
throw FailInfoException.BAD_REQUEST;
}
}
if (X509Util.getCommonName(csrReqInfo.getSubject()) == null) {
throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, "tid=" + tid + ": no CommonName in requested subject");
}
NameId userIdent = null;
String challengePwd = CaUtil.getChallengePassword(csrReqInfo);
if (challengePwd != null) {
String[] strs = challengePwd.split(":");
if (strs == null || strs.length != 2) {
LOG.warn("tid={}: challengePassword does not have the format <user>:<password>", tid);
throw FailInfoException.BAD_REQUEST;
}
String user = strs[0];
String password = strs[1];
userIdent = ca.authenticateUser(user, password.getBytes());
if (userIdent == null) {
LOG.warn("tid={}: could not authenticate user {}", tid, user);
throw FailInfoException.BAD_REQUEST;
}
}
if (selfSigned) {
if (MessageType.PKCSReq != mt) {
LOG.warn("tid={}: self-signed certificate is not permitted for" + " messageType {}", tid, mt);
throw FailInfoException.BAD_REQUEST;
}
if (userIdent == null) {
LOG.warn("tid={}: could not extract user & password from challengePassword" + ", which are required for self-signed signature certificate", tid);
throw FailInfoException.BAD_REQUEST;
}
} else {
// certificate is known by the CA
if (userIdent == null) {
// up to draft-nourse-scep-23 the client sends all messages to enroll
// certificate via MessageType PKCSReq
KnowCertResult knowCertRes = ca.knowsCertificate(reqSignatureCert);
if (!knowCertRes.isKnown()) {
LOG.warn("tid={}: signature certificate is not trusted by the CA", tid);
throw FailInfoException.BAD_REQUEST;
}
Integer userId = knowCertRes.getUserId();
if (userId == null) {
LOG.warn("tid={}: could not extract user from the signature cert", tid);
throw FailInfoException.BAD_REQUEST;
}
userIdent = ca.getUserIdent(userId);
}
// end if
}
// end if
ByUserRequestorInfo requestor = ca.getByUserRequestor(userIdent);
checkUserPermission(requestor, certProfileName);
byte[] tidBytes = getTransactionIdBytes(tid);
Extensions extensions = CaUtil.getExtensions(csrReqInfo);
CertTemplateData certTemplateData = new CertTemplateData(csrReqInfo.getSubject(), csrReqInfo.getSubjectPublicKeyInfo(), (Date) null, (Date) null, extensions, certProfileName);
X509CertificateInfo cert = ca.generateCertificate(certTemplateData, requestor, RequestType.SCEP, tidBytes, msgId);
/* Don't save SCEP message, since it contains password in plaintext
if (ca.getCaInfo().isSaveRequest() && cert.getCert().getCertId() != null) {
byte[] encodedRequest;
try {
encodedRequest = requestContent.getEncoded();
} catch (IOException ex) {
LOG.warn("could not encode request");
encodedRequest = null;
}
if (encodedRequest != null) {
long reqId = ca.addRequest(encodedRequest);
ca.addRequestCert(reqId, cert.getCert().getCertId());
}
}*/
signedData = buildSignedData(cert.getCert().getCert());
break;
case CertPoll:
IssuerAndSubject is = IssuerAndSubject.getInstance(req.getMessageData());
audit(event, CaAuditConstants.NAME_issuer, X509Util.getRfc4519Name(is.getIssuer()));
audit(event, CaAuditConstants.NAME_subject, X509Util.getRfc4519Name(is.getSubject()));
ensureIssuedByThisCa(caX500Name, is.getIssuer());
signedData = pollCert(ca, is.getSubject(), req.getTransactionId());
break;
case GetCert:
IssuerAndSerialNumber isn = IssuerAndSerialNumber.getInstance(req.getMessageData());
BigInteger serial = isn.getSerialNumber().getPositiveValue();
audit(event, CaAuditConstants.NAME_issuer, X509Util.getRfc4519Name(isn.getName()));
audit(event, CaAuditConstants.NAME_serial, LogUtil.formatCsn(serial));
ensureIssuedByThisCa(caX500Name, isn.getName());
signedData = getCert(ca, isn.getSerialNumber().getPositiveValue());
break;
case GetCRL:
isn = IssuerAndSerialNumber.getInstance(req.getMessageData());
serial = isn.getSerialNumber().getPositiveValue();
audit(event, CaAuditConstants.NAME_issuer, X509Util.getRfc4519Name(isn.getName()));
audit(event, CaAuditConstants.NAME_serial, LogUtil.formatCsn(serial));
ensureIssuedByThisCa(caX500Name, isn.getName());
signedData = getCrl(ca, serial);
break;
default:
LOG.error("unknown SCEP messageType '{}'", req.getMessageType());
throw FailInfoException.BAD_REQUEST;
}
// end switch<
ContentInfo ci = new ContentInfo(CMSObjectIdentifiers.signedData, signedData);
rep.setMessageData(ci);
rep.setPkiStatus(PkiStatus.SUCCESS);
} catch (FailInfoException ex) {
LogUtil.error(LOG, ex);
rep.setPkiStatus(PkiStatus.FAILURE);
rep.setFailInfo(ex.getFailInfo());
}
return rep;
}
use of org.gudy.bouncycastle.asn1.cms.ContentInfo in project xipki by xipki.
the class HttpScepServlet method service.
@Override
public FullHttpResponse service(FullHttpRequest request, ServletURI servletUri, SSLSession sslSession, SslReverseProxyMode sslReverseProxyMode) throws Exception {
HttpVersion version = request.protocolVersion();
HttpMethod method = request.method();
boolean viaPost;
if (method == HttpMethod.POST) {
viaPost = true;
} else if (method == HttpMethod.GET) {
viaPost = false;
} else {
return createErrorResponse(version, HttpResponseStatus.METHOD_NOT_ALLOWED);
}
String scepName = null;
String certProfileName = null;
if (servletUri.getPath().length() > 1) {
String scepPath = servletUri.getPath();
if (scepPath.endsWith(CGI_PROGRAM)) {
// skip also the first char (which is always '/')
String path = scepPath.substring(1, scepPath.length() - CGI_PROGRAM_LEN);
String[] tokens = path.split("/");
if (tokens.length == 2) {
scepName = tokens[0];
certProfileName = tokens[1].toLowerCase();
}
}
// end if
}
if (scepName == null || certProfileName == null) {
return createErrorResponse(version, HttpResponseStatus.NOT_FOUND);
}
AuditService auditService = auditServiceRegister.getAuditService();
AuditEvent event = new AuditEvent(new Date());
event.setApplicationName("SCEP");
event.setName(CaAuditConstants.NAME_PERF);
event.addEventData(CaAuditConstants.NAME_SCEP_name, scepName + "/" + certProfileName);
event.addEventData(CaAuditConstants.NAME_reqType, RequestType.SCEP.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) {
auditMessage = "responderManager in servlet not configured";
LOG.error(auditMessage);
auditLevel = AuditLevel.ERROR;
auditStatus = AuditStatus.FAILED;
return createErrorResponse(version, HttpResponseStatus.INTERNAL_SERVER_ERROR);
}
Scep responder = responderManager.getScep(scepName);
if (responder == null || !responder.isOnService() || !responder.supportsCertProfile(certProfileName)) {
auditMessage = "unknown SCEP '" + scepName + "/" + certProfileName + "'";
LOG.warn(auditMessage);
auditStatus = AuditStatus.FAILED;
return createErrorResponse(version, HttpResponseStatus.NOT_FOUND);
}
String operation = servletUri.getParameter("operation");
event.addEventData(CaAuditConstants.NAME_SCEP_operation, operation);
if ("PKIOperation".equalsIgnoreCase(operation)) {
CMSSignedData reqMessage;
// parse the request
try {
byte[] content;
if (viaPost) {
content = readContent(request);
} else {
String b64 = servletUri.getParameter("message");
content = Base64.decode(b64);
}
reqMessage = new CMSSignedData(content);
} catch (Exception ex) {
final String msg = "invalid request";
LogUtil.error(LOG, ex, msg);
auditMessage = msg;
auditStatus = AuditStatus.FAILED;
return createErrorResponse(version, HttpResponseStatus.BAD_REQUEST);
}
ContentInfo ci;
try {
ci = responder.servicePkiOperation(reqMessage, certProfileName, msgId, event);
} catch (MessageDecodingException ex) {
final String msg = "could not decrypt and/or verify the request";
LogUtil.error(LOG, ex, msg);
auditMessage = msg;
auditStatus = AuditStatus.FAILED;
return createErrorResponse(version, HttpResponseStatus.BAD_REQUEST);
} catch (OperationException ex) {
ErrorCode code = ex.getErrorCode();
HttpResponseStatus httpCode;
switch(code) {
case ALREADY_ISSUED:
case CERT_REVOKED:
case CERT_UNREVOKED:
httpCode = HttpResponseStatus.FORBIDDEN;
break;
case BAD_CERT_TEMPLATE:
case BAD_REQUEST:
case BAD_POP:
case INVALID_EXTENSION:
case UNKNOWN_CERT:
case UNKNOWN_CERT_PROFILE:
httpCode = HttpResponseStatus.BAD_REQUEST;
break;
case NOT_PERMITTED:
httpCode = HttpResponseStatus.UNAUTHORIZED;
break;
case SYSTEM_UNAVAILABLE:
httpCode = HttpResponseStatus.SERVICE_UNAVAILABLE;
break;
case CRL_FAILURE:
case DATABASE_FAILURE:
case SYSTEM_FAILURE:
httpCode = HttpResponseStatus.INTERNAL_SERVER_ERROR;
break;
default:
httpCode = HttpResponseStatus.INTERNAL_SERVER_ERROR;
break;
}
auditMessage = ex.getMessage();
LogUtil.error(LOG, ex, auditMessage);
auditStatus = AuditStatus.FAILED;
return createErrorResponse(version, httpCode);
}
byte[] bodyBytes = ci.getEncoded();
return createOKResponse(version, CT_RESPONSE, bodyBytes);
} else if (Operation.GetCACaps.getCode().equalsIgnoreCase(operation)) {
// CA-Ident is ignored
byte[] caCapsBytes = responder.getCaCaps().getBytes();
return createOKResponse(version, ScepConstants.CT_TEXT_PLAIN, caCapsBytes);
} else if (Operation.GetCACert.getCode().equalsIgnoreCase(operation)) {
// CA-Ident is ignored
byte[] respBytes = responder.getCaCertResp().getBytes();
return createOKResponse(version, ScepConstants.CT_X509_CA_RA_CERT, respBytes);
} else if (Operation.GetNextCACert.getCode().equalsIgnoreCase(operation)) {
auditMessage = "SCEP operation '" + operation + "' is not permitted";
auditStatus = AuditStatus.FAILED;
return createErrorResponse(version, HttpResponseStatus.FORBIDDEN);
} else {
auditMessage = "unknown SCEP operation '" + operation + "'";
auditStatus = AuditStatus.FAILED;
return createErrorResponse(version, HttpResponseStatus.BAD_REQUEST);
}
} catch (Throwable th) {
if (th instanceof EOFException) {
final String msg = "connection reset by peer";
if (LOG.isWarnEnabled()) {
LogUtil.warn(LOG, th, msg);
}
LOG.debug(msg, th);
} else {
LOG.error("Throwable thrown, this should not happen!", th);
}
auditLevel = AuditLevel.ERROR;
auditStatus = AuditStatus.FAILED;
auditMessage = "internal error";
return createErrorResponse(version, HttpResponseStatus.INTERNAL_SERVER_ERROR);
} finally {
audit(auditService, event, auditLevel, auditStatus, auditMessage);
}
}
use of org.gudy.bouncycastle.asn1.cms.ContentInfo in project xipki by xipki.
the class ScepServlet method service.
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
boolean post;
String method = req.getMethod();
if ("GET".equals(method)) {
post = false;
} else if ("POST".equals(method)) {
post = true;
} else {
resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
return;
}
AuditEvent event = new AuditEvent();
event.setName(ScepAuditConstants.NAME_PERF);
event.putEventData(ScepAuditConstants.NAME_servletPath, req.getServletPath());
AuditLevel auditLevel = AuditLevel.INFO;
String auditMessage = null;
try {
CaCaps caCaps = responder.getCaCaps();
if (post && !caCaps.containsCapability(CaCapability.POSTPKIOperation)) {
auditMessage = "HTTP POST is not supported";
auditLevel = AuditLevel.ERROR;
resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
}
String operation = req.getParameter("operation");
event.putEventData(ScepAuditConstants.NAME_operation, operation);
if ("PKIOperation".equalsIgnoreCase(operation)) {
CMSSignedData reqMessage;
// parse the request
try {
byte[] content = post ? ScepUtil.read(req.getInputStream()) : Base64.decode(req.getParameter("message"));
reqMessage = new CMSSignedData(content);
} catch (Exception ex) {
auditMessage = "invalid request";
auditLevel = AuditLevel.ERROR;
resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
}
ContentInfo ci;
try {
ci = responder.servicePkiOperation(reqMessage, event);
} catch (MessageDecodingException ex) {
auditMessage = "could not decrypt and/or verify the request";
auditLevel = AuditLevel.ERROR;
resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
} catch (CaException ex) {
auditMessage = "system internal error";
auditLevel = AuditLevel.ERROR;
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
byte[] respBytes = ci.getEncoded();
sendToResponse(resp, CT_RESPONSE, respBytes);
} else if (Operation.GetCACaps.getCode().equalsIgnoreCase(operation)) {
// CA-Ident is ignored
byte[] caCapsBytes = responder.getCaCaps().getBytes();
sendToResponse(resp, ScepConstants.CT_TEXT_PLAIN, caCapsBytes);
} else if (Operation.GetCACert.getCode().equalsIgnoreCase(operation)) {
// CA-Ident is ignored
byte[] respBytes;
String ct;
if (responder.getRaEmulator() == null) {
ct = ScepConstants.CT_X509_CA_CERT;
respBytes = responder.getCaEmulator().getCaCertBytes();
} else {
ct = ScepConstants.CT_X509_CA_RA_CERT;
CMSSignedDataGenerator cmsSignedDataGen = new CMSSignedDataGenerator();
try {
cmsSignedDataGen.addCertificate(new X509CertificateHolder(responder.getCaEmulator().getCaCert()));
ct = ScepConstants.CT_X509_CA_RA_CERT;
cmsSignedDataGen.addCertificate(new X509CertificateHolder(responder.getRaEmulator().getRaCert()));
CMSSignedData degenerateSignedData = cmsSignedDataGen.generate(new CMSAbsentContent());
respBytes = degenerateSignedData.getEncoded();
} catch (CMSException ex) {
auditMessage = "system internal error";
auditLevel = AuditLevel.ERROR;
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
}
sendToResponse(resp, ct, respBytes);
} else if (Operation.GetNextCACert.getCode().equalsIgnoreCase(operation)) {
if (responder.getNextCaAndRa() == null) {
auditMessage = "SCEP operation '" + operation + "' is not permitted";
auditLevel = AuditLevel.ERROR;
resp.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
try {
NextCaMessage nextCaMsg = new NextCaMessage();
nextCaMsg.setCaCert(ScepUtil.toX509Cert(responder.getNextCaAndRa().getCaCert()));
if (responder.getNextCaAndRa().getRaCert() != null) {
X509Certificate raCert = ScepUtil.toX509Cert(responder.getNextCaAndRa().getRaCert());
nextCaMsg.setRaCerts(Arrays.asList(raCert));
}
ContentInfo signedData = responder.encode(nextCaMsg);
byte[] respBytes = signedData.getEncoded();
sendToResponse(resp, ScepConstants.CT_X509_NEXT_CA_CERT, respBytes);
} catch (Exception ex) {
auditMessage = "system internal error";
auditLevel = AuditLevel.ERROR;
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
} else {
auditMessage = "unknown SCEP operation '" + operation + "'";
auditLevel = AuditLevel.ERROR;
resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
}
// end if ("PKIOperation".equalsIgnoreCase(operation))
} catch (EOFException ex) {
LOG.warn("connection reset by peer", ex);
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
} catch (Throwable th) {
LOG.error("Throwable thrown, this should not happen!", th);
auditLevel = AuditLevel.ERROR;
auditMessage = "internal error";
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
} finally {
if (event.getLevel() != AuditLevel.ERROR) {
event.setLevel(auditLevel);
}
if (auditMessage != null) {
event.putEventData("error", auditMessage);
}
event.log(LOG);
}
// end try
}
use of org.gudy.bouncycastle.asn1.cms.ContentInfo in project xipki by xipki.
the class DecodedPkiMessage method decode.
@SuppressWarnings("unchecked")
public static DecodedPkiMessage decode(CMSSignedData pkiMessage, EnvelopedDataDecryptor recipient, CollectionStore<X509CertificateHolder> certStore) throws MessageDecodingException {
ScepUtil.requireNonNull("pkiMessage", pkiMessage);
ScepUtil.requireNonNull("recipient", recipient);
SignerInformationStore signerStore = pkiMessage.getSignerInfos();
Collection<SignerInformation> signerInfos = signerStore.getSigners();
if (signerInfos.size() != 1) {
throw new MessageDecodingException("number of signerInfos is not 1, but " + signerInfos.size());
}
SignerInformation signerInfo = signerInfos.iterator().next();
SignerId sid = signerInfo.getSID();
Collection<?> signedDataCerts = null;
if (certStore != null) {
signedDataCerts = certStore.getMatches(sid);
}
if (signedDataCerts == null || signedDataCerts.isEmpty()) {
signedDataCerts = pkiMessage.getCertificates().getMatches(signerInfo.getSID());
}
if (signedDataCerts == null || signedDataCerts.size() != 1) {
throw new MessageDecodingException("could not find embedded certificate to verify the signature");
}
AttributeTable signedAttrs = signerInfo.getSignedAttributes();
if (signedAttrs == null) {
throw new MessageDecodingException("missing SCEP attributes");
}
Date signingTime = null;
// signingTime
ASN1Encodable attrValue = ScepUtil.getFirstAttrValue(signedAttrs, CMSAttributes.signingTime);
if (attrValue != null) {
signingTime = Time.getInstance(attrValue).getDate();
}
// transactionId
String str = getPrintableStringAttrValue(signedAttrs, ScepObjectIdentifiers.ID_TRANSACTION_ID);
if (str == null || str.isEmpty()) {
throw new MessageDecodingException("missing required SCEP attribute transactionId");
}
TransactionId transactionId = new TransactionId(str);
// messageType
Integer intValue = getIntegerPrintStringAttrValue(signedAttrs, ScepObjectIdentifiers.ID_MESSAGE_TYPE);
if (intValue == null) {
throw new MessageDecodingException("tid " + transactionId.getId() + ": missing required SCEP attribute messageType");
}
MessageType messageType;
try {
messageType = MessageType.forValue(intValue);
} catch (IllegalArgumentException ex) {
throw new MessageDecodingException("tid " + transactionId.getId() + ": invalid messageType '" + intValue + "'");
}
// senderNonce
Nonce senderNonce = getNonceAttrValue(signedAttrs, ScepObjectIdentifiers.ID_SENDER_NONCE);
if (senderNonce == null) {
throw new MessageDecodingException("tid " + transactionId.getId() + ": missing required SCEP attribute senderNonce");
}
DecodedPkiMessage ret = new DecodedPkiMessage(transactionId, messageType, senderNonce);
if (signingTime != null) {
ret.setSigningTime(signingTime);
}
Nonce recipientNonce = null;
try {
recipientNonce = getNonceAttrValue(signedAttrs, ScepObjectIdentifiers.ID_RECIPIENT_NONCE);
} catch (MessageDecodingException ex) {
ret.setFailureMessage("could not parse recipientNonce: " + ex.getMessage());
}
if (recipientNonce != null) {
ret.setRecipientNonce(recipientNonce);
}
PkiStatus pkiStatus = null;
FailInfo failInfo = null;
if (MessageType.CertRep == messageType) {
// pkiStatus
try {
intValue = getIntegerPrintStringAttrValue(signedAttrs, ScepObjectIdentifiers.ID_PKI_STATUS);
} catch (MessageDecodingException ex) {
ret.setFailureMessage("could not parse pkiStatus: " + ex.getMessage());
return ret;
}
if (intValue == null) {
ret.setFailureMessage("missing required SCEP attribute pkiStatus");
return ret;
}
try {
pkiStatus = PkiStatus.forValue(intValue);
} catch (IllegalArgumentException ex) {
ret.setFailureMessage("invalid pkiStatus '" + intValue + "'");
return ret;
}
ret.setPkiStatus(pkiStatus);
// failureInfo
if (pkiStatus == PkiStatus.FAILURE) {
try {
intValue = getIntegerPrintStringAttrValue(signedAttrs, ScepObjectIdentifiers.ID_FAILINFO);
} catch (MessageDecodingException ex) {
ret.setFailureMessage("could not parse failInfo: " + ex.getMessage());
return ret;
}
if (intValue == null) {
ret.setFailureMessage("missing required SCEP attribute failInfo");
return ret;
}
try {
failInfo = FailInfo.forValue(intValue);
} catch (IllegalArgumentException ex) {
ret.setFailureMessage("invalid failInfo '" + intValue + "'");
return ret;
}
ret.setFailInfo(failInfo);
}
// end if(pkiStatus == PkiStatus.FAILURE)
}
// end if (MessageType.CertRep == messageType)
// other signedAttributes
Attribute[] attrs = signedAttrs.toASN1Structure().getAttributes();
for (Attribute attr : attrs) {
ASN1ObjectIdentifier type = attr.getAttrType();
if (!SCEP_ATTR_TYPES.contains(type)) {
ret.addSignendAttribute(type, attr.getAttrValues().getObjectAt(0));
}
}
// unsignedAttributes
AttributeTable unsignedAttrs = signerInfo.getUnsignedAttributes();
attrs = (unsignedAttrs == null) ? null : unsignedAttrs.toASN1Structure().getAttributes();
if (attrs != null) {
for (Attribute attr : attrs) {
ASN1ObjectIdentifier type = attr.getAttrType();
ret.addUnsignendAttribute(type, attr.getAttrValues().getObjectAt(0));
}
}
ASN1ObjectIdentifier digestAlgOid = signerInfo.getDigestAlgorithmID().getAlgorithm();
ret.setDigestAlgorithm(digestAlgOid);
String sigAlgOid = signerInfo.getEncryptionAlgOID();
if (!PKCSObjectIdentifiers.rsaEncryption.getId().equals(sigAlgOid)) {
ASN1ObjectIdentifier tmpDigestAlgOid;
try {
tmpDigestAlgOid = ScepUtil.extractDigesetAlgorithmIdentifier(signerInfo.getEncryptionAlgOID(), signerInfo.getEncryptionAlgParams());
} catch (Exception ex) {
final String msg = "could not extract digest algorithm from signerInfo.signatureAlgorithm: " + ex.getMessage();
LOG.error(msg);
LOG.debug(msg, ex);
ret.setFailureMessage(msg);
return ret;
}
if (!digestAlgOid.equals(tmpDigestAlgOid)) {
ret.setFailureMessage("digestAlgorithm and encryptionAlgorithm do not use the same digestAlgorithm");
return ret;
}
// end if
}
// end if
X509CertificateHolder tmpSignerCert = (X509CertificateHolder) signedDataCerts.iterator().next();
X509Certificate signerCert;
try {
signerCert = ScepUtil.toX509Cert(tmpSignerCert.toASN1Structure());
} catch (CertificateException ex) {
final String msg = "could not construct X509Certificate: " + ex.getMessage();
LOG.error(msg);
LOG.debug(msg, ex);
ret.setFailureMessage(msg);
return ret;
}
ret.setSignatureCert(signerCert);
// validate the signature
SignerInformationVerifier verifier;
try {
verifier = new JcaSimpleSignerInfoVerifierBuilder().build(tmpSignerCert);
} catch (OperatorCreationException | CertificateException ex) {
final String msg = "could not build signature verifier: " + ex.getMessage();
LOG.error(msg);
LOG.debug(msg, ex);
ret.setFailureMessage(msg);
return ret;
}
boolean signatureValid;
try {
signatureValid = signerInfo.verify(verifier);
} catch (CMSException ex) {
final String msg = "could not verify the signature: " + ex.getMessage();
LOG.error(msg);
LOG.debug(msg, ex);
ret.setFailureMessage(msg);
return ret;
}
ret.setSignatureValid(signatureValid);
if (!signatureValid) {
return ret;
}
if (MessageType.CertRep == messageType && (pkiStatus == PkiStatus.FAILURE | pkiStatus == PkiStatus.PENDING)) {
return ret;
}
// MessageData
CMSTypedData signedContent = pkiMessage.getSignedContent();
ASN1ObjectIdentifier signedContentType = signedContent.getContentType();
if (!CMSObjectIdentifiers.envelopedData.equals(signedContentType)) {
// fall back: some SCEP client, such as JSCEP use id-data
if (!CMSObjectIdentifiers.data.equals(signedContentType)) {
ret.setFailureMessage("either id-envelopedData or id-data is excepted, but not '" + signedContentType.getId());
return ret;
}
}
CMSEnvelopedData envData;
try {
envData = new CMSEnvelopedData((byte[]) signedContent.getContent());
} catch (CMSException ex) {
final String msg = "could not create the CMSEnvelopedData: " + ex.getMessage();
LOG.error(msg);
LOG.debug(msg, ex);
ret.setFailureMessage(msg);
return ret;
}
ret.setContentEncryptionAlgorithm(envData.getContentEncryptionAlgorithm().getAlgorithm());
byte[] encodedMessageData;
try {
encodedMessageData = recipient.decrypt(envData);
} catch (MessageDecodingException ex) {
final String msg = "could not create the CMSEnvelopedData: " + ex.getMessage();
LOG.error(msg);
LOG.debug(msg, ex);
ret.setFailureMessage(msg);
ret.setDecryptionSuccessful(false);
return ret;
}
ret.setDecryptionSuccessful(true);
try {
if (MessageType.PKCSReq == messageType || MessageType.RenewalReq == messageType || MessageType.UpdateReq == messageType) {
CertificationRequest messageData = CertificationRequest.getInstance(encodedMessageData);
ret.setMessageData(messageData);
} else if (MessageType.CertPoll == messageType) {
IssuerAndSubject messageData = IssuerAndSubject.getInstance(encodedMessageData);
ret.setMessageData(messageData);
} else if (MessageType.GetCert == messageType || MessageType.GetCRL == messageType) {
IssuerAndSerialNumber messageData = IssuerAndSerialNumber.getInstance(encodedMessageData);
ret.setMessageData(messageData);
ret.setMessageData(messageData);
} else if (MessageType.CertRep == messageType) {
ContentInfo ci = ContentInfo.getInstance(encodedMessageData);
ret.setMessageData(ci);
} else {
throw new RuntimeException("should not reach here, unknown messageType " + messageType);
}
} catch (Exception ex) {
final String msg = "could not parse the messageData: " + ex.getMessage();
LOG.error(msg);
LOG.debug(msg, ex);
ret.setFailureMessage(msg);
return ret;
}
return ret;
}
Aggregations