List of usage examples for org.bouncycastle.asn1.x500 X500Name toString
public String toString()
From source file:org.ejbca.core.protocol.cmp.CrmfMessageHandler.java
License:Open Source License
/** Method that takes care of RA mode operations, i.e. when the message is authenticated with a common secret using password based encryption (pbe). * This method will verify the pbe and if ok will automatically create/edit a user and issue the certificate. In RA mode we assume that the RA knows what it is doing. * /* w ww .j a va 2s. c o m*/ * @param msg * @param crmfreq * @param authenticated if the CMP message has already been authenticated in another way or not * @return IResponseMessage that can be sent back to the client * @throws AuthorizationDeniedException * @throws EjbcaException * @throws ClassNotFoundException * @throws CesecoreException */ private ResponseMessage handleRaMessage(final BaseCmpMessage msg, final CrmfRequestMessage crmfreq, boolean authenticated) throws AuthorizationDeniedException, EjbcaException, CesecoreException { final int eeProfileId; // The endEntityProfile to be used when adding users in RA mode. final String certProfileName; // The certificate profile to use when adding users in RA mode. final int certProfileId; final int requestId = crmfreq.getRequestId(); final int requestType = crmfreq.getRequestType(); // Try to find a HMAC/SHA1 protection key final String keyId = CmpMessageHelper.getStringFromOctets(crmfreq.getHeader().getSenderKID()); int caId = 0; // The CA to user when adding users in RA mode try { eeProfileId = getUsedEndEntityProfileId(keyId); caId = getUsedCaId(keyId, eeProfileId); certProfileName = getUsedCertProfileName(keyId, eeProfileId); certProfileId = getUsedCertProfileId(certProfileName); } catch (CADoesntExistsException e) { LOG.info(INTRES.getLocalizedMessage(CMP_ERRORGENERAL, e.getMessage()), e); return CmpMessageHelper.createErrorMessage(msg, FailInfo.INCORRECT_DATA, e.getMessage(), requestId, requestType, null, keyId, this.responseProt); } ResponseMessage resp = null; // The CMP response message to be sent back to the client //Check the request's authenticity CAInfo cainfo = this.caSession.getCAInfoInternal(caId, null, true); final VerifyPKIMessage messageVerifyer = new VerifyPKIMessage(cainfo, this.confAlias, admin, caSession, endEntityAccessSession, certStoreSession, authorizationSession, endEntityProfileSession, authenticationProviderSession, eeManagementSession, this.cmpConfiguration); ICMPAuthenticationModule authenticationModule = messageVerifyer .getUsedAuthenticationModule(crmfreq.getPKIMessage(), null, authenticated); if (authenticationModule == null) { String errmsg = messageVerifyer.getErrorMessage(); LOG.info(errmsg); return CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.BAD_MESSAGE_CHECK, errmsg); } try { // Create a username and password and register the new user in EJBCA final UsernameGenerator gen = UsernameGenerator.getInstance(this.usernameGenParams); // Don't convert this DN to an ordered EJBCA DN string with CertTools.stringToBCDNString because we don't want double escaping of some characters final RequestMessage req = this.extendedUserDataHandler != null ? this.extendedUserDataHandler.processRequestMessage(crmfreq, certProfileName, cmpConfiguration.getUnidDataSource(this.confAlias)) : crmfreq; final X500Name dnname = req.getRequestX500Name(); if (LOG.isDebugEnabled()) { LOG.debug("Creating username from base dn: " + dnname.toString()); } final String username = StringTools.stripUsername(gen.generateUsername(dnname.toString())); final String pwd; if (StringUtils.equals(authenticationModule.getName(), CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE)) { pwd = authenticationModule.getAuthenticationString(); } else if (StringUtils.equals(authenticationModule.getName(), CmpConfiguration.AUTHMODULE_HMAC)) { if (StringUtils.equals(this.userPwdParams, "random")) { if (LOG.isDebugEnabled()) { LOG.debug("Setting 12 char random user password."); } final IPasswordGenerator pwdgen = PasswordGeneratorFactory .getInstance(PasswordGeneratorFactory.PASSWORDTYPE_ALLPRINTABLE); pwd = pwdgen.getNewPassword(12, 12); } else { if (LOG.isDebugEnabled()) { LOG.debug("Setting fixed user password from config."); } pwd = this.userPwdParams; } } else { //This should not run since an error would have occurred earlier if the authentication module was unknown final String errMsg = "Unknown authentication module."; LOG.error(errMsg); return CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.BAD_MESSAGE_CHECK, errMsg); } // AltNames may be in the request template final String altNames = req.getRequestAltNames(); final String email; final List<String> emails = CertTools.getEmailFromDN(altNames); emails.addAll(CertTools.getEmailFromDN(dnname.toString())); if (!emails.isEmpty()) { email = emails.get(0); // Use rfc822name or first SubjectDN email address as user email address if available } else { email = null; } final ExtendedInformation ei; if (this.allowCustomCertSerno) { // Don't even try to parse out the field if it is not allowed final BigInteger customCertSerno = crmfreq.getSubjectCertSerialNo(); if (customCertSerno != null) { // If we have a custom certificate serial number in the request, we will pass it on to the UserData object ei = new ExtendedInformation(); ei.setCertificateSerialNumber(customCertSerno); if (LOG.isDebugEnabled()) { LOG.debug("Custom certificate serial number: " + customCertSerno.toString(16)); } } else { ei = null; } } else { ei = null; } final EndEntityInformation userdata = new EndEntityInformation(username, dnname.toString(), caId, altNames, email, EndEntityConstants.STATUS_NEW, new EndEntityType(EndEntityTypes.ENDUSER), eeProfileId, certProfileId, null, null, SecConst.TOKEN_SOFT_BROWSERGEN, 0, ei); userdata.setPassword(pwd); // Set so we have the right params in the call to processCertReq. // Username and pwd in the EndEntityInformation and the IRequestMessage must match crmfreq.setUsername(username); crmfreq.setPassword(pwd); if (msg.getHeader().getProtectionAlg() != null) { crmfreq.setPreferredDigestAlg(AlgorithmTools .getDigestFromSigAlg(crmfreq.getHeader().getProtectionAlg().getAlgorithm().getId())); } // Set all protection parameters CmpPbeVerifyer verifyer = null; if (StringUtils.equals(authenticationModule.getName(), CmpConfiguration.AUTHMODULE_HMAC)) { final HMACAuthenticationModule hmacmodule = (HMACAuthenticationModule) authenticationModule; verifyer = hmacmodule.getCmpPbeVerifyer(); final String pbeDigestAlg = verifyer.getOwfOid(); final String pbeMacAlg = verifyer.getMacOid(); final int pbeIterationCount = verifyer.getIterationCount(); final String raSecret = verifyer.getLastUsedRaSecret(); if (LOG.isDebugEnabled()) { LOG.debug("responseProt=" + this.responseProt + ", pbeDigestAlg=" + pbeDigestAlg + ", pbeMacAlg=" + pbeMacAlg + ", keyId=" + keyId + ", raSecret=" + (raSecret == null ? "null" : "not null")); } if (StringUtils.equals(this.responseProt, "pbe")) { crmfreq.setPbeParameters(keyId, raSecret, pbeDigestAlg, pbeMacAlg, pbeIterationCount); } } try { try { if (LOG.isDebugEnabled()) { LOG.debug("Creating new request with eeProfileId '" + eeProfileId + "', certProfileId '" + certProfileId + "', caId '" + caId + "'"); } resp = this.certificateRequestSession.processCertReq(this.admin, userdata, req, org.ejbca.core.protocol.cmp.CmpResponseMessage.class); } catch (EndEntityExistsException e) { final String updateMsg = INTRES.getLocalizedMessage("cmp.erroradduserupdate", username); LOG.info(updateMsg); // Try again resp = this.certificateRequestSession.processCertReq(this.admin, userdata, req, org.ejbca.core.protocol.cmp.CmpResponseMessage.class); } } catch (UserDoesntFullfillEndEntityProfile e) { LOG.info(INTRES.getLocalizedMessage(CMP_ERRORADDUSER, username), e); resp = CmpMessageHelper.createErrorMessage(msg, FailInfo.INCORRECT_DATA, e.getMessage(), requestId, requestType, verifyer, keyId, this.responseProt); } catch (ApprovalException e) { LOG.info(INTRES.getLocalizedMessage(CMP_ERRORADDUSER, username), e); resp = CmpMessageHelper.createErrorMessage(msg, FailInfo.NOT_AUTHORIZED, e.getMessage(), requestId, requestType, verifyer, keyId, this.responseProt); } catch (EndEntityExistsException e) { LOG.info(INTRES.getLocalizedMessage(CMP_ERRORADDUSER, username), e); resp = CmpMessageHelper.createErrorMessage(msg, FailInfo.NOT_AUTHORIZED, e.getMessage(), requestId, requestType, verifyer, keyId, this.responseProt); } catch (CertificateExtensionException e) { LOG.info(INTRES.getLocalizedMessage(CMP_ERRORADDUSER, username), e); resp = CmpMessageHelper.createErrorMessage(msg, FailInfo.BAD_REQUEST, e.getMessage(), requestId, requestType, verifyer, keyId, this.responseProt); } } catch (HandlerException e) { LOG.error(INTRES.getLocalizedMessage("cmp.errorexthandlerexec"), e); resp = CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.BAD_MESSAGE_CHECK, e.getMessage()); } return resp; }
From source file:org.ejbca.core.protocol.cmp.CrmfRATcpRequestTest.java
License:Open Source License
@Test public void test02CrmfOkUser() throws Exception { // Create a new good user final X500Name dn = new X500Name("C=SE,O=PrimeKey,CN=cmptest"); createCmpUser(CMP_USERNAME, dn.toString()); try {//from w w w . jav a2 s . c o m byte[] nonce = CmpMessageHelper.createSenderNonce(); byte[] transid = CmpMessageHelper.createSenderNonce(); PKIMessage one = genCertReq(issuerDN, dn, this.keys, this.cacert, nonce, transid, true, null, null, null, null, null, null); PKIMessage req = protectPKIMessage(one, false, PBEPASSWORD, 567); CertReqMessages ir = (CertReqMessages) req.getBody().getContent(); int reqId = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue(); assertNotNull(req); ByteArrayOutputStream bao = new ByteArrayOutputStream(); DEROutputStream out = new DEROutputStream(bao); out.writeObject(req); byte[] ba = bao.toByteArray(); // Send request and receive response byte[] resp = sendCmpTcp(ba, 5); checkCmpResponseGeneral(resp, issuerDN, dn, this.cacert, nonce, transid, true, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId()); checkCmpCertRepMessage(dn, this.cacert, resp, reqId); // Send a confirm message to the CA String hash = "foo123"; PKIMessage confirm = genCertConfirm(dn, this.cacert, nonce, transid, hash, reqId); assertNotNull(confirm); bao = new ByteArrayOutputStream(); out = new DEROutputStream(bao); out.writeObject(confirm); ba = bao.toByteArray(); // Send request and receive response resp = sendCmpTcp(ba, 5); checkCmpResponseGeneral(resp, issuerDN, dn, this.cacert, nonce, transid, false, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId()); checkCmpPKIConfirmMessage(dn, this.cacert, resp); } finally { this.endEntityManagementSession.deleteUser(ADMIN, CMP_USERNAME); } }
From source file:org.ejbca.core.protocol.cmp.CrmfRequestMessage.java
License:Open Source License
@Override public String getIssuerDN() { String ret = null;/*from w ww . j a va 2s. c om*/ final CertTemplate templ = getReq().getCertReq().getCertTemplate(); final X500Name name = templ.getIssuer(); if (name != null) { ret = CertTools.stringToBCDNString(name.toString()); } else { ret = defaultCADN; } if (log.isDebugEnabled()) { log.debug("Issuer DN is: " + ret); } return ret; }
From source file:org.ejbca.core.protocol.cmp.CrmfRequestMessage.java
License:Open Source License
@Override public String getRequestDN() { String ret = null;//from w ww .j a va 2 s . com final X500Name name = getRequestX500Name(); if (name != null) { ret = CertTools.stringToBCDNString(name.toString()); } if (log.isDebugEnabled()) { log.debug("Request DN is: " + ret); } return ret; }
From source file:org.ejbca.core.protocol.cmp.CrmfRequestMessage.java
License:Open Source License
@Override public boolean verify() throws InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException { boolean ret = false; final ProofOfPossession pop = getReq().getPopo(); if (log.isDebugEnabled()) { log.debug("allowRaVerifyPopo: " + allowRaVerifyPopo); log.debug("pop.getRaVerified(): " + (pop.getType() == ProofOfPossession.TYPE_RA_VERIFIED)); }//from ww w. j a v a2 s . c o m if (allowRaVerifyPopo && (pop.getType() == ProofOfPossession.TYPE_RA_VERIFIED)) { ret = true; } else if (pop.getType() == ProofOfPossession.TYPE_SIGNING_KEY) { try { final POPOSigningKey sk = (POPOSigningKey) pop.getObject(); final POPOSigningKeyInput pski = sk.getPoposkInput(); ASN1Encodable protObject = pski; // Use of POPOSigningKeyInput or not, as described in RFC4211, section 4.1. if (pski == null) { if (log.isDebugEnabled()) { log.debug("Using CertRequest as POPO input because POPOSigningKeyInput is missing."); } protObject = getReq().getCertReq(); } else { // Assume POPOSigningKeyInput with the public key and name, MUST be the same as in the request according to RFC4211 if (log.isDebugEnabled()) { log.debug("Using POPOSigningKeyInput as POPO input."); } final CertRequest req = getReq().getCertReq(); // If subject is present in cert template it must be the same as in POPOSigningKeyInput final X500Name subject = req.getCertTemplate().getSubject(); if (subject != null && !subject.toString().equals(pski.getSender().getName().toString())) { log.info("Subject '" + subject.toString() + "', is not equal to '" + pski.getSender().toString() + "'."); protObject = null; // pski is not a valid protection object } // If public key is present in cert template it must be the same as in POPOSigningKeyInput final SubjectPublicKeyInfo pk = req.getCertTemplate().getPublicKey(); if (pk != null && !Arrays.areEqual(pk.getEncoded(), pski.getPublicKey().getEncoded())) { log.info( "Subject key in cert template, is not equal to subject key in POPOSigningKeyInput."); protObject = null; // pski is not a valid protection object } } // If a protectObject is present we extract the bytes and verify it if (protObject != null) { final ByteArrayOutputStream bao = new ByteArrayOutputStream(); new DEROutputStream(bao).writeObject(protObject); final byte[] protBytes = bao.toByteArray(); final AlgorithmIdentifier algId = sk.getAlgorithmIdentifier(); if (log.isDebugEnabled()) { log.debug( "POP protection bytes length: " + (protBytes != null ? protBytes.length : "null")); log.debug("POP algorithm identifier is: " + algId.getAlgorithm().getId()); } final Signature sig = Signature.getInstance(algId.getAlgorithm().getId(), "BC"); sig.initVerify(getRequestPublicKey()); sig.update(protBytes); final DERBitString bs = sk.getSignature(); ret = sig.verify(bs.getBytes()); if (log.isDebugEnabled()) { log.debug("POP verify returns: " + ret); } } } catch (IOException e) { log.error("Error encoding CertReqMsg: ", e); } catch (SignatureException e) { log.error("SignatureException verifying POP: ", e); } } return ret; }
From source file:org.ejbca.core.protocol.cmp.CrmfRequestMessage.java
License:Open Source License
public String getSubjectDN() { String ret = null;/* w ww .j a v a 2s . c o m*/ final CertTemplate templ = getReq().getCertReq().getCertTemplate(); final X500Name name = templ.getSubject(); if (name != null) { ret = CertTools.stringToBCDNString(name.toString()); } return ret; }
From source file:org.ejbca.core.protocol.cmp.CrmfRequestMessageTest.java
License:Open Source License
@Test public void testCrmfRequestUsernameGeneratorFromDN() throws IOException, ClassNotFoundException, NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException { CryptoProviderTools.installBCProviderIfNotAvailable(); {//www.j a v a 2 s .co m final PKIMessage myPKIMessage = createPKIMessage("CN=bogusIssuer", "CN=subject,SN=000106716,O=Org,C=SE"); final CrmfRequestMessage crmf = new CrmfRequestMessage(myPKIMessage, "CN=SomeCA", true, null); final X500Name dnname = crmf.getRequestX500Name(); final UsernameGeneratorParams params = new UsernameGeneratorParams(); params.setMode(UsernameGeneratorParams.DN); UsernameGenerator gen = UsernameGenerator.getInstance(params); String username = gen.generateUsername(dnname.toString()); assertEquals("Username was not constructed properly from DN (CN)", "subject", username); params.setDNGeneratorComponent(""); gen = UsernameGenerator.getInstance(params); username = gen.generateUsername(dnname.toString()); assertEquals("Username was not constructed properly from DN", "CN=subject,SN=000106716,O=Org,C=SE", username); } { // DN order the other way around, should give username the other way around as well final PKIMessage myPKIMessage = createPKIMessage("CN=bogusIssuer", "C=SE,O=Org,SERIALNUMBER=000106716,CN=subject"); final CrmfRequestMessage crmf = new CrmfRequestMessage(myPKIMessage, "CN=SomeCA", true, null); final X500Name dnname = crmf.getRequestX500Name(); final UsernameGeneratorParams params = new UsernameGeneratorParams(); params.setMode(UsernameGeneratorParams.DN); UsernameGenerator gen = UsernameGenerator.getInstance(params); String username = gen.generateUsername(dnname.toString()); assertEquals("Username was not constructed properly from DN (CN)", "subject", username); params.setDNGeneratorComponent(""); gen = UsernameGenerator.getInstance(params); username = gen.generateUsername(dnname.toString()); assertEquals("Username was not constructed properly from DN", "C=SE,O=Org,SN=000106716,CN=subject", username); } }
From source file:org.ejbca.core.protocol.cmp.CrmfRequestTest.java
License:Open Source License
@Test public void test11IncludingCertChainInSignedCMPResponse() throws Exception { //---------- Create SubCA signed by testx509ca (rootCA) ------------- // String subcaDN = "CN=SubTestCA"; int subcaID = subcaDN.hashCode(); int cryptoTokenId = CryptoTokenTestUtils.createCryptoTokenForCA(ADMIN, null, true, false, subcaDN, "1024"); final String username = "cmptest"; try {/*from w w w . j a v a 2 s . c o m*/ final CAToken catoken = CaTestUtils.createCaToken(cryptoTokenId, AlgorithmConstants.SIGALG_SHA256_WITH_RSA, AlgorithmConstants.SIGALG_SHA256_WITH_RSA); final List<ExtendedCAServiceInfo> extendedCaServices = new ArrayList<ExtendedCAServiceInfo>(2); extendedCaServices.add(new KeyRecoveryCAServiceInfo(ExtendedCAServiceInfo.STATUS_ACTIVE)); String caname = CertTools.getPartFromDN(subcaDN, "CN"); boolean ldapOrder = !CertTools.isDNReversed(subcaDN); X509CAInfo cainfo = new X509CAInfo(subcaDN, caname, CAConstants.CA_ACTIVE, CertificateProfileConstants.CERTPROFILE_FIXED_SUBCA, 3650, this.caid, this.testx509ca.getCertificateChain(), catoken); cainfo.setDescription("JUnit RSA SubCA"); cainfo.setExtendedCAServiceInfos(extendedCaServices); cainfo.setUseLdapDnOrder(ldapOrder); cainfo.setCmpRaAuthSecret("foo123"); CAAdminSessionRemote caAdminSession = EjbRemoteHelper.INSTANCE .getRemoteSession(CAAdminSessionRemote.class); caAdminSession.createCA(ADMIN, cainfo); assertTrue(this.caSession.existsCa(subcaID)); cainfo = (X509CAInfo) this.caSession.getCAInfo(ADMIN, subcaID); X509Certificate subcaCert = (X509Certificate) cainfo.getCertificateChain().iterator().next(); // --------- Create a user ----------------- // boolean userExists = false; final X500Name userDN = new X500Name("C=SE,O=PrimeKey,CN=cmptest"); EndEntityInformation user = new EndEntityInformation("cmptest", userDN.toString(), subcaID, null, "cmptest@primekey.se", new EndEntityType(EndEntityTypes.ENDUSER), // SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, this.eepDnOverrideId, this.cpDnOverrideId, SecConst.TOKEN_SOFT_PEM, 0, null); user.setPassword("foo123"); try { this.endEntityManagementSession.addUser(ADMIN, user, true); log.debug("created user: cmptest, foo123, " + userDN); } catch (Exception e) { userExists = true; } if (userExists) { log.debug("User cmptest already exists."); this.endEntityManagementSession.changeUser(ADMIN, user, true); this.endEntityManagementSession.setUserStatus(ADMIN, "cmptest", EndEntityConstants.STATUS_NEW); log.debug("Reset status to NEW"); } assertTrue(this.endEntityManagementSession.existsUser("cmptest")); EndEntityAccessSessionRemote eeAccessSession = EjbRemoteHelper.INSTANCE .getRemoteSession(EndEntityAccessSessionRemote.class); EndEntityInformation ee = eeAccessSession.findUser(ADMIN, "cmptest"); assertEquals(subcaID, ee.getCAId()); // -------- generate and send a CMP request -------------- // byte[] nonce = CmpMessageHelper.createSenderNonce(); byte[] transid = CmpMessageHelper.createSenderNonce(); PKIMessage req = genCertReq(subcaDN, userDN, this.keys, subcaCert, nonce, transid, false, null, null, null, null, null, null); assertNotNull(req); CertReqMessages ir = (CertReqMessages) req.getBody().getContent(); int reqId = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue(); ByteArrayOutputStream bao = new ByteArrayOutputStream(); DEROutputStream out = new DEROutputStream(bao); out.writeObject(req); byte[] ba = bao.toByteArray(); // Send request and receive response byte[] resp = sendCmpHttp(ba, 200, cmpAlias); checkCmpResponseGeneral(resp, subcaDN, userDN, subcaCert, nonce, transid, true, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId()); final X509Certificate cert = checkCmpCertRepMessage(userDN, subcaCert, resp, reqId); assertNotNull(cert); // ------- Check that the entire certificate chain is in the extraCerts field in the response PKIMessage respMsg = null; ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(resp)); try { respMsg = PKIMessage.getInstance(asn1InputStream.readObject()); } finally { asn1InputStream.close(); } assertNotNull(respMsg); CMPCertificate[] certChain = respMsg.getExtraCerts(); assertEquals(2, certChain.length); assertEquals(subcaDN, certChain[0].getX509v3PKCert().getSubject().toString()); assertEquals(ISSUER_DN, certChain[1].getX509v3PKCert().getSubject().toString()); } finally { try { this.endEntityManagementSession.deleteUser(ADMIN, username); } catch (NotFoundException e) { // A test probably failed before creating the entity log.debug("Failed to delete user: " + username); } CryptoTokenTestUtils.removeCryptoToken(null, cryptoTokenId); // Remove CA certificate of CA that we will remove Collection<Certificate> certs = this.caSession.getCAInfo(ADMIN, subcaID).getCertificateChain(); this.internalCertStoreSession.removeCertificate(certs.iterator().next()); // Remove the CA itself this.caSession.removeCA(ADMIN, subcaID); } }
From source file:org.ejbca.core.protocol.cmp.GeneralCmpMessage.java
License:Open Source License
public GeneralCmpMessage(final PKIMessage msg) { final PKIBody body = msg.getBody(); final int tag = body.getType(); if (tag == 19) { // this is a PKIConfirmContent if (log.isDebugEnabled()) { log.debug("Received a PKIConfirm message"); }//from w w w. j av a 2 s . c om // This is a null message, so there is nothing to get here //DERNull obj = body.getConf(); } if (tag == 24) { // this is a CertConfirmContent if (log.isDebugEnabled()) { log.debug("Received a Cert Confirm message"); } final CertConfirmContent obj = (CertConfirmContent) body.getContent(); CertStatus cs; try { cs = CertStatus.getInstance(obj.toASN1Primitive()); } catch (Exception e) { cs = CertStatus.getInstance(((DERSequence) obj.toASN1Primitive()).getObjectAt(0)); } final PKIStatusInfo status = cs.getStatusInfo(); if (status != null) { final int st = status.getStatus().intValue(); if (st != 0) { final String errMsg = intres.getLocalizedMessage("cmp.errorcertconfirmstatus", Integer.valueOf(st)); log.error(errMsg); // TODO: if it is rejected, we should revoke the cert? } } } if (tag == 11) { // this is a RevReqContent, if (log.isDebugEnabled()) { log.debug("Received a RevReqContent"); } final RevReqContent rr = (RevReqContent) body.getContent(); RevDetails rd; try { rd = rr.toRevDetailsArray()[0]; } catch (Exception e) { log.debug( "Could not parse the revocation request. Trying to parse it as novosec generated message."); rd = CmpMessageHelper.getNovosecRevDetails(rr); log.debug("Succeeded in parsing the novosec generated request."); } final CertTemplate ct = rd.getCertDetails(); final ASN1Integer serno = ct.getSerialNumber(); final X500Name issuer = ct.getIssuer(); if ((serno != null) && (issuer != null)) { final String errMsg = intres.getLocalizedMessage("cmp.receivedrevreq", issuer.toString(), serno.getValue().toString(16)); log.info(errMsg); } else { final String errMsg = intres.getLocalizedMessage("cmp.receivedrevreqnoissuer"); log.info(errMsg); } } setMessage(msg); final PKIHeader header = msg.getHeader(); if (header.getTransactionID() != null) { final byte[] val = header.getTransactionID().getOctets(); if (val != null) { setTransactionId(new String(Base64.encode(val))); } } if (header.getSenderNonce() != null) { final byte[] val = header.getSenderNonce().getOctets(); if (val != null) { setSenderNonce(new String(Base64.encode(val))); } } setRecipient(header.getRecipient()); setSender(header.getSender()); }
From source file:org.ejbca.core.protocol.cmp.RevocationMessageHandler.java
License:Open Source License
public ResponseMessage handleMessage(final BaseCmpMessage msg, boolean authenticated) { if (LOG.isTraceEnabled()) { LOG.trace(">handleMessage"); }/*from w w w . ja va2s. c o m*/ CA ca = null; try { final String caDN = msg.getHeader().getRecipient().getName().toString(); final int caId = CertTools.stringToBCDNString(caDN).hashCode(); if (LOG.isDebugEnabled()) { LOG.debug("CA DN is '" + caDN + "' and resulting caId is " + caId + ", after CertTools.stringToBCDNString conversion."); } ca = caSession.getCA(admin, caId); } catch (CADoesntExistsException e) { final String errMsg = "CA with DN '" + msg.getHeader().getRecipient().getName().toString() + "' is unknown"; LOG.info(errMsg); return CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.BAD_REQUEST, errMsg); } catch (AuthorizationDeniedException e) { LOG.info(INTRES.getLocalizedMessage(CMP_ERRORGENERAL, e.getMessage()), e); return CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.INCORRECT_DATA, e.getMessage()); } ResponseMessage resp = null; // if version == 1 it is cmp1999 and we should not return a message back // Try to find a HMAC/SHA1 protection key final String keyId = CmpMessageHelper.getStringFromOctets(msg.getHeader().getSenderKID()); ResponseStatus status = ResponseStatus.FAILURE; FailInfo failInfo = FailInfo.BAD_MESSAGE_CHECK; String failText = null; //Verify the authenticity of the message final VerifyPKIMessage messageVerifyer = new VerifyPKIMessage(ca.getCAInfo(), this.confAlias, admin, caSession, endEntityAccessSession, certificateStoreSession, authorizationSession, endEntityProfileSession, authenticationProviderSession, endEntityManagementSession, this.cmpConfiguration); ICMPAuthenticationModule authenticationModule = messageVerifyer .getUsedAuthenticationModule(msg.getMessage(), null, authenticated); if (authenticationModule == null) { LOG.info(messageVerifyer.getErrorMessage()); return CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.BAD_MESSAGE_CHECK, messageVerifyer.getErrorMessage()); } // If authentication was correct, we will now try to find the certificate to revoke final PKIMessage pkimsg = msg.getMessage(); final PKIBody body = pkimsg.getBody(); final RevReqContent rr = (RevReqContent) body.getContent(); RevDetails rd; try { rd = rr.toRevDetailsArray()[0]; } catch (Exception e) { LOG.debug("Could not parse the revocation request. Trying to parse it as novosec generated message."); rd = CmpMessageHelper.getNovosecRevDetails(rr); LOG.debug("Succeeded in parsing the novosec generated request."); } final CertTemplate ct = rd.getCertDetails(); final ASN1Integer serno = ct.getSerialNumber(); final X500Name issuer = ct.getIssuer(); // Get the revocation reason. // For CMPv1 this can be a simple DERBitString or it can be a requested CRL Entry Extension // If there exists CRL Entry Extensions we will use that, because it's the only thing allowed in CMPv2 int reason = RevokedCertInfo.REVOCATION_REASON_UNSPECIFIED; final ASN1OctetString reasonoctets = rd.getCrlEntryDetails().getExtension(Extension.reasonCode) .getExtnValue(); DERBitString reasonbits; try { reasonbits = new DERBitString(reasonoctets.getEncoded()); } catch (IOException e1) { LOG.info(INTRES.getLocalizedMessage(CMP_ERRORGENERAL, e1.getMessage()), e1); return CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.INCORRECT_DATA, e1.getMessage()); } if (reasonbits != null) { reason = CertTools.bitStringToRevokedCertInfo(reasonbits); if (LOG.isDebugEnabled()) { LOG.debug("CMPv1 revocation reason: " + reason); } } final Extensions crlExt = rd.getCrlEntryDetails(); if (crlExt != null) { final Extension ext = crlExt.getExtension(Extension.reasonCode); if (ext != null) { try { final ASN1InputStream ai = new ASN1InputStream(ext.getExtnValue().getOctets()); final ASN1Primitive obj = ai.readObject(); final ASN1Enumerated crlreason = ASN1Enumerated.getInstance(obj); // RevokedCertInfo.REVOCATION_REASON_AACOMPROMISE are the same integer values as the CRL reason extension code reason = crlreason.getValue().intValue(); if (LOG.isDebugEnabled()) { LOG.debug("CRLReason extension: " + reason); } ai.close(); } catch (IOException e) { LOG.info("Exception parsin CRL reason extension: ", e); } } else { if (LOG.isDebugEnabled()) { LOG.debug("No CRL reason code extension present."); } } } else { if (LOG.isDebugEnabled()) { LOG.debug("No CRL entry extensions present"); } } if ((serno != null) && (issuer != null)) { final String iMsg = INTRES.getLocalizedMessage("cmp.receivedrevreq", issuer.toString(), serno.getValue().toString(16)); LOG.info(iMsg); try { endEntityManagementSession.revokeCert(admin, serno.getValue(), issuer.toString(), reason); status = ResponseStatus.SUCCESS; } catch (AuthorizationDeniedException e) { failInfo = FailInfo.NOT_AUTHORIZED; final String errMsg = INTRES.getLocalizedMessage("cmp.errornotauthrevoke", issuer.toString(), serno.getValue().toString(16)); failText = errMsg; LOG.info(failText); } catch (FinderException e) { failInfo = FailInfo.BAD_CERTIFICATE_ID; final String errMsg = INTRES.getLocalizedMessage("cmp.errorcertnofound", issuer.toString(), serno.getValue().toString(16)); failText = errMsg; // This is already info logged in endEntityManagementSession.revokeCert // LOG.info(failText); } catch (WaitingForApprovalException e) { status = ResponseStatus.GRANTED_WITH_MODS; } catch (ApprovalException e) { failInfo = FailInfo.BAD_REQUEST; final String errMsg = INTRES.getLocalizedMessage("cmp.erroralreadyrequested"); failText = errMsg; LOG.info(failText); } catch (AlreadyRevokedException e) { failInfo = FailInfo.BAD_REQUEST; final String errMsg = INTRES.getLocalizedMessage("cmp.erroralreadyrevoked"); failText = errMsg; // This is already info logged in endEntityManagementSession.revokeCert // LOG.info(failText); } } else { failInfo = FailInfo.BAD_CERTIFICATE_ID; final String errMsg = INTRES.getLocalizedMessage("cmp.errormissingissuerrevoke", issuer.toString(), serno.getValue().toString(16)); failText = errMsg; LOG.info(failText); } if (LOG.isDebugEnabled()) { LOG.debug("Creating a PKI revocation message response"); } final CmpRevokeResponseMessage rresp = new CmpRevokeResponseMessage(); rresp.setRecipientNonce(msg.getSenderNonce()); rresp.setSenderNonce(new String(Base64.encode(CmpMessageHelper.createSenderNonce()))); rresp.setSender(msg.getRecipient()); rresp.setRecipient(msg.getSender()); rresp.setTransactionId(msg.getTransactionId()); rresp.setFailInfo(failInfo); rresp.setFailText(failText); rresp.setStatus(status); if (StringUtils.equals(responseProtection, "pbe")) { final HMACAuthenticationModule hmacmodule = (HMACAuthenticationModule) authenticationModule; final String owfAlg = hmacmodule.getCmpPbeVerifyer().getOwfOid(); final String macAlg = hmacmodule.getCmpPbeVerifyer().getMacOid(); final int iterationCount = 1024; final String cmpRaAuthSecret = hmacmodule.getAuthenticationString(); if ((owfAlg != null) && (macAlg != null) && (keyId != null) && (cmpRaAuthSecret != null)) { // Set all protection parameters if (LOG.isDebugEnabled()) { LOG.debug(responseProtection + ", " + owfAlg + ", " + macAlg + ", " + keyId + ", " + cmpRaAuthSecret); } rresp.setPbeParameters(keyId, cmpRaAuthSecret, owfAlg, macAlg, iterationCount); } } else if (StringUtils.equals(responseProtection, "signature")) { try { final CryptoToken cryptoToken = cryptoTokenSession .getCryptoToken(ca.getCAToken().getCryptoTokenId()); final String aliasCertSign = ca.getCAToken() .getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN); rresp.setSignKeyInfo(ca.getCertificateChain(), cryptoToken.getPrivateKey(aliasCertSign), cryptoToken.getSignProviderName()); if (msg.getHeader().getProtectionAlg() != null) { rresp.setPreferredDigestAlg(AlgorithmTools .getDigestFromSigAlg(msg.getHeader().getProtectionAlg().getAlgorithm().getId())); } } catch (CryptoTokenOfflineException e) { LOG.error(e.getLocalizedMessage(), e); } } resp = rresp; try { resp.create(); } catch (InvalidKeyException e) { String errMsg = INTRES.getLocalizedMessage("cmp.errorgeneral"); LOG.error(errMsg, e); } catch (NoSuchAlgorithmException e) { String errMsg = INTRES.getLocalizedMessage("cmp.errorgeneral"); LOG.error(errMsg, e); } catch (NoSuchProviderException e) { String errMsg = INTRES.getLocalizedMessage("cmp.errorgeneral"); LOG.error(errMsg, e); } catch (CertificateEncodingException e) { String errMsg = INTRES.getLocalizedMessage("cmp.errorgeneral"); LOG.error(errMsg, e); } catch (CRLException e) { String errMsg = INTRES.getLocalizedMessage("cmp.errorgeneral"); LOG.error(errMsg, e); } return resp; }