private PKIMessage addProtection(PKIMessage pkiMessage, AuditEvent event) { try { return CmpUtil.addProtection(pkiMessage, getSigner(), getSender(), getCmpControl().sendResponderCert()); } catch (Exception ex) { LogUtil.error(LOG, ex, "could not add protection to the PKI message"); PKIStatusInfo status = generateRejectionStatus( PKIFailureInfo.systemFailure, "could not sign the PKIMessage"); event.setLevel(AuditLevel.ERROR); event.setStatus(AuditStatus.FAILED); event.addEventData(CaAuditConstants.NAME_message, "could not sign the PKIMessage"); PKIBody body = new PKIBody(PKIBody.TYPE_ERROR, new ErrorMsgContent(status)); return new PKIMessage(pkiMessage.getHeader(), body); } }
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); }
public void testMacProtectedMessage() throws Exception { KeyPairGenerator kGen = KeyPairGenerator.getInstance("RSA", BC); kGen.initialize(512); KeyPair kp = kGen.generateKeyPair(); X509CertificateHolder cert = makeV3Certificate(kp, "CN=Test", kp, "CN=Test"); GeneralName sender = new GeneralName(new X500Name("CN=Sender")); GeneralName recipient = new GeneralName(new X500Name("CN=Recip")); ProtectedPKIMessage message = new ProtectedPKIMessageBuilder(sender, recipient) .setBody(new PKIBody(PKIBody.TYPE_INIT_REP, CertRepMessage.getInstance(new DERSequence(new DERSequence())))) .addCMPCertificate(cert) .build(new PKMACBuilder(new JcePKMACValuesCalculator().setProvider(BC)).build("secret".toCharArray())); PKMACBuilder pkMacBuilder = new PKMACBuilder(new JcePKMACValuesCalculator().setProvider(BC)); assertTrue(message.verify(pkMacBuilder, "secret".toCharArray())); assertEquals(sender, message.getHeader().getSender()); assertEquals(recipient, message.getHeader().getRecipient()); }
/** * Set the body for the new message * * @param body the message body. * @return the current builder instance. */ public ProtectedPKIMessageBuilder setBody(PKIBody body) { this.body = body; return this; }
/** * handle the PKI body with the choice {@code cr}. * */ private PKIBody processCr(PKIMessage request, CmpRequestorInfo requestor, ASN1OctetString tid, PKIHeader reqHeader, CertReqMessages cr, CmpControl cmpControl, String msgId, AuditEvent event) { CertRepMessage repMessage = processCertReqMessages(request, requestor, tid, reqHeader, cr, false, cmpControl, msgId, event); return new PKIBody(PKIBody.TYPE_CERT_REP, repMessage); }
private PKIBody processKur(PKIMessage request, CmpRequestorInfo requestor, ASN1OctetString tid, PKIHeader reqHeader, CertReqMessages kur, CmpControl cmpControl, String msgId, AuditEvent event) { CertRepMessage repMessage = processCertReqMessages(request, requestor, tid, reqHeader, kur, true, cmpControl, msgId, event); return new PKIBody(PKIBody.TYPE_KEY_UPDATE_REP, repMessage); }
/** * handle the PKI body with the choice {@code cr}. * */ private PKIBody processCcp(PKIMessage request, CmpRequestorInfo requestor, ASN1OctetString tid, PKIHeader reqHeader, CertReqMessages cr, CmpControl cmpControl, String msgId, AuditEvent event) { CertRepMessage repMessage = processCertReqMessages(request, requestor, tid, reqHeader, cr, false, cmpControl, msgId, event); return new PKIBody(PKIBody.TYPE_CROSS_CERT_REP, repMessage); }
private static PKIBody buildErrorMsgPkiBody(PKIStatus pkiStatus, int failureInfo, String statusMessage) { PKIFreeText pkiStatusMsg = (statusMessage == null) ? null : new PKIFreeText(statusMessage); ErrorMsgContent emc = new ErrorMsgContent( new PKIStatusInfo(pkiStatus, pkiStatusMsg, new PKIFailureInfo(failureInfo))); return new PKIBody(PKIBody.TYPE_ERROR, emc); }
public void testProtectedMessage() throws Exception { KeyPairGenerator kGen = KeyPairGenerator.getInstance("RSA", BC); kGen.initialize(512); KeyPair kp = kGen.generateKeyPair(); X509CertificateHolder cert = makeV3Certificate(kp, "CN=Test", kp, "CN=Test"); GeneralName sender = new GeneralName(new X500Name("CN=Sender")); GeneralName recipient = new GeneralName(new X500Name("CN=Recip")); ContentSigner signer = new JcaContentSignerBuilder("MD5WithRSAEncryption").setProvider(BC).build(kp.getPrivate()); ProtectedPKIMessage message = new ProtectedPKIMessageBuilder(sender, recipient) .setBody(new PKIBody(PKIBody.TYPE_INIT_REP, CertRepMessage.getInstance(new DERSequence(new DERSequence())))) .addCMPCertificate(cert) .build(signer); X509Certificate jcaCert = new JcaX509CertificateConverter().setProvider(BC).getCertificate(message.getCertificates()[0]); ContentVerifierProvider verifierProvider = new JcaContentVerifierProviderBuilder().setProvider(BC).build(jcaCert.getPublicKey()); assertTrue(message.verify(verifierProvider)); assertEquals(sender, message.getHeader().getSender()); assertEquals(recipient, message.getHeader().getRecipient()); }
public void testConfirmationMessage() throws Exception { KeyPairGenerator kGen = KeyPairGenerator.getInstance("RSA", BC); kGen.initialize(512); KeyPair kp = kGen.generateKeyPair(); X509CertificateHolder cert = makeV3Certificate(kp, "CN=Test", kp, "CN=Test"); GeneralName sender = new GeneralName(new X500Name("CN=Sender")); GeneralName recipient = new GeneralName(new X500Name("CN=Recip")); CertificateConfirmationContent content = new CertificateConfirmationContentBuilder() .addAcceptedCertificate(cert, BigInteger.valueOf(1)) .build(new JcaDigestCalculatorProviderBuilder().build()); ContentSigner signer = new JcaContentSignerBuilder("MD5WithRSAEncryption").setProvider(BC).build(kp.getPrivate()); ProtectedPKIMessage message = new ProtectedPKIMessageBuilder(sender, recipient) .setBody(new PKIBody(PKIBody.TYPE_CERT_CONFIRM, content.toASN1Structure())) .addCMPCertificate(cert) .build(signer); X509Certificate jcaCert = new JcaX509CertificateConverter().setProvider(BC).getCertificate(message.getCertificates()[0]); ContentVerifierProvider verifierProvider = new JcaContentVerifierProviderBuilder().setProvider(BC).build(jcaCert.getPublicKey()); assertTrue(message.verify(verifierProvider)); assertEquals(sender, message.getHeader().getSender()); assertEquals(recipient, message.getHeader().getRecipient()); content = new CertificateConfirmationContent(CertConfirmContent.getInstance(message.getBody().getContent())); CertificateStatus[] statusList = content.getStatusMessages(); assertEquals(1, statusList.length); assertTrue(statusList[0].isVerified(cert, new JcaDigestCalculatorProviderBuilder().setProvider(BC).build())); }
public void testSubsequentMessage() throws Exception { KeyPairGenerator kGen = KeyPairGenerator.getInstance("RSA", BC); kGen.initialize(512); KeyPair kp = kGen.generateKeyPair(); X509CertificateHolder cert = makeV3Certificate(kp, "CN=Test", kp, "CN=Test"); ContentSigner signer = new JcaContentSignerBuilder("SHA256withRSA").setProvider(BC).build( kp.getPrivate()); GeneralName user = new GeneralName(new X500Name("CN=Test")); CertificateRequestMessageBuilder builder = new JcaCertificateRequestMessageBuilder( BigInteger.valueOf(1)).setPublicKey(kp.getPublic()).setProofOfPossessionSubsequentMessage( SubsequentMessage.encrCert); ProtectedPKIMessage certRequestMsg = new ProtectedPKIMessageBuilder(user, user).setTransactionID(new byte[] { 1, 2, 3, 4, 5 }).setBody( new PKIBody(PKIBody.TYPE_KEY_UPDATE_REQ, new CertReqMessages(builder.build().toASN1Structure()))).addCMPCertificate( cert).build(signer); ProtectedPKIMessage msg = new ProtectedPKIMessage(new GeneralPKIMessage(certRequestMsg.toASN1Structure().getEncoded())); CertReqMessages reqMsgs = CertReqMessages.getInstance(msg.getBody().getContent()); CertReqMsg reqMsg = reqMsgs.toCertReqMsgArray()[0]; assertEquals(ProofOfPossession.TYPE_KEY_ENCIPHERMENT, reqMsg.getPopo().getType()); }
public PKIBody getBody() { return pkiMessage.getBody(); }
private byte[] calculateSignature(ContentSigner signer, PKIHeader header, PKIBody body) throws IOException { ASN1EncodableVector v = new ASN1EncodableVector(); v.add(header); v.add(body); OutputStream sOut = signer.getOutputStream(); sOut.write(new DERSequence(v).getEncoded(ASN1Encoding.DER)); sOut.close(); return signer.getSignature(); }
private byte[] calculateMac(MacCalculator macCalculator, PKIHeader header, PKIBody body) throws IOException { ASN1EncodableVector v = new ASN1EncodableVector(); v.add(header); v.add(body); OutputStream sOut = macCalculator.getOutputStream(); sOut.write(new DERSequence(v).getEncoded(ASN1Encoding.DER)); sOut.close(); return macCalculator.getMac(); }
/** * 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().popoAlgoValidator())) { 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_CERT_PROFILE); String str = keyvalues.value(CmpUtf8Pairs.KEY_NOT_BEFORE); if (str != null) { notBefore = DateUtil.parseUtcTimeyyyyMMddhhmmss(str); } str = keyvalues.value(CmpUtf8Pairs.KEY_NOT_AFTER); if (str != null) { notAfter = DateUtil.parseUtcTimeyyyyMMddhhmmss(str); } } if (certprofileName == null) { certResp = buildErrorCertResponse(certReqId, PKIFailureInfo.badCertTemplate, "badCertTemplate", null); } else { certprofileName = certprofileName.toUpperCase(); 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.sendCaCert()) { caPubs = new CMPCertificate[]{ca.caInfo().certInCmpFormat()}; } CertRepMessage repMessage = new CertRepMessage(caPubs, new CertResponse[]{certResp}); return new PKIBody(PKIBody.TYPE_CERT_REP, repMessage); }
private PKIBody confirmCertificates(ASN1OctetString transactionId, CertConfirmContent certConf, String msgId) { CertStatus[] certStatuses = certConf.toCertStatusArray(); boolean successful = true; for (CertStatus certStatus : certStatuses) { ASN1Integer certReqId = certStatus.getCertReqId(); byte[] certHash = certStatus.getCertHash().getOctets(); X509CertificateInfo certInfo = pendingCertPool.removeCertificate( transactionId.getOctets(), certReqId.getPositiveValue(), certHash); if (certInfo == null) { if (LOG.isWarnEnabled()) { LOG.warn("no cert under transactionId={}, certReqId={} and certHash=0X{}", transactionId, certReqId.getPositiveValue(), Hex.encode(certHash)); } continue; } PKIStatusInfo statusInfo = certStatus.getStatusInfo(); boolean accept = true; if (statusInfo != null) { int status = statusInfo.getStatus().intValue(); if (PKIStatus.GRANTED != status && PKIStatus.GRANTED_WITH_MODS != status) { accept = false; } } if (accept) { continue; } BigInteger serialNumber = certInfo.cert().cert().getSerialNumber(); X509Ca ca = getCa(); try { ca.revokeCertificate(serialNumber, CrlReason.CESSATION_OF_OPERATION, new Date(), msgId); } catch (OperationException ex) { LogUtil.warn(LOG, ex, "could not revoke certificate ca=" + ca.caInfo().ident() + " serialNumber=" + LogUtil.formatCsn(serialNumber)); } successful = false; } // all other certificates should be revoked if (revokePendingCertificates(transactionId, msgId)) { successful = false; } if (successful) { return new PKIBody(PKIBody.TYPE_CONFIRM, DERNull.INSTANCE); } ErrorMsgContent emc = new ErrorMsgContent( new PKIStatusInfo(PKIStatus.rejection, null, new PKIFailureInfo(PKIFailureInfo.systemFailure))); return new PKIBody(PKIBody.TYPE_ERROR, emc); }
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.code(); 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.code()) { 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; } } } // end for 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); } }
/** * Return the message body. * * @return the message's PKIBody structure. */ public PKIBody getBody() { return pkiMessage.getBody(); }