List of usage examples for javax.ejb EJBException EJBException
public EJBException(Exception ex)
From source file:org.ejbca.core.ejb.ra.UserAdminSessionBean.java
private void sendNotification(Admin admin, UserDataVO data, int newstatus) { if (data == null) { if (log.isDebugEnabled()) { log.debug("No UserData, no notification sent."); }//from w ww . j a va2s.c o m return; } String useremail = data.getEmail(); if (log.isTraceEnabled()) { log.trace(">sendNotification: user=" + data.getUsername() + ", email=" + useremail); } // Make check if we should send notifications at all if (((data.getType() & SecConst.USER_SENDNOTIFICATION) != 0)) { int profileId = data.getEndEntityProfileId(); EndEntityProfile profile = endEntityProfileSession.getEndEntityProfile(admin, profileId); Collection<UserNotification> l = profile.getUserNotifications(); if (log.isDebugEnabled()) { log.debug("Number of user notifications: " + l.size()); } Iterator<UserNotification> i = l.iterator(); String rcptemail = useremail; // Default value while (i.hasNext()) { UserNotification not = i.next(); Collection<String> events = not.getNotificationEventsCollection(); if (events.contains(String.valueOf(newstatus))) { if (log.isDebugEnabled()) { log.debug("Status is " + newstatus + ", notification sent for notificationevents: " + not.getNotificationEvents()); } try { if (StringUtils.equals(not.getNotificationRecipient(), UserNotification.RCPT_USER)) { rcptemail = useremail; } else if (StringUtils.contains(not.getNotificationRecipient(), UserNotification.RCPT_CUSTOM)) { rcptemail = "custom"; // Just if this fail it will // say that sending to user // with email "custom" failed. // Plug-in mechanism for retrieving custom // notification email recipient addresses if (not.getNotificationRecipient().length() < 6) { String msg = intres.getLocalizedMessage("ra.errorcustomrcptshort", not.getNotificationRecipient()); log.error(msg); } else { String cp = not.getNotificationRecipient().substring(7); if (StringUtils.isNotEmpty(cp)) { ICustomNotificationRecipient plugin = (ICustomNotificationRecipient) Thread .currentThread().getContextClassLoader().loadClass(cp).newInstance(); rcptemail = plugin.getRecipientEmails(data); if (StringUtils.isEmpty(rcptemail)) { String msg = intres.getLocalizedMessage("ra.errorcustomnoemail", not.getNotificationRecipient()); log.error(msg); } else { if (log.isDebugEnabled()) { log.debug("Custom notification recipient plugin returned email: " + rcptemail); } } } else { String msg = intres.getLocalizedMessage("ra.errorcustomnoclasspath", not.getNotificationRecipient()); log.error(msg); } } } else { // Just a plain email address specified in the // recipient field rcptemail = not.getNotificationRecipient(); } if (StringUtils.isEmpty(rcptemail)) { String msg = intres.getLocalizedMessage("ra.errornotificationnoemail", data.getUsername()); throw new Exception(msg); } // Get the administrators DN from the admin certificate, // if one exists // When approvals is used, this will be the DN of the // admin that approves the request Certificate adminCert = admin.getAdminInformation().getX509Certificate(); String approvalAdminDN = CertTools.getSubjectDN(adminCert); if (log.isDebugEnabled()) { log.debug("approvalAdminDN: " + approvalAdminDN); } UserNotificationParamGen paramGen = new UserNotificationParamGen(data, approvalAdminDN, findUser(admin, admin.getUsername())); /* * substitute any $ fields in the receipient and from * fields */ rcptemail = paramGen.interpolate(rcptemail); String fromemail = paramGen.interpolate(not.getNotificationSender()); String subject = paramGen.interpolate(not.getNotificationSubject()); String message = paramGen.interpolate(not.getNotificationMessage()); MailSender.sendMailOrThrow(fromemail, Arrays.asList(rcptemail), MailSender.NO_CC, subject, message, MailSender.NO_ATTACHMENTS); String logmsg = intres.getLocalizedMessage("ra.sentnotification", data.getUsername(), rcptemail); logSession.log(admin, data.getCAId(), LogConstants.MODULE_RA, new Date(), data.getUsername(), null, LogConstants.EVENT_INFO_NOTIFICATION, logmsg); } catch (Exception e) { String msg = intres.getLocalizedMessage("ra.errorsendnotification", data.getUsername(), rcptemail); log.error(msg, e); try { logSession.log(admin, data.getCAId(), LogConstants.MODULE_RA, new Date(), data.getUsername(), null, LogConstants.EVENT_ERROR_NOTIFICATION, msg); } catch (Exception f) { throw new EJBException(f); } } } else { // if (events.contains(String.valueOf(newstatus))) if (log.isDebugEnabled()) { log.debug("Status is " + newstatus + ", no notification sent for notificationevents: " + not.getNotificationEvents()); } } } } else { // if ( ((data.getType() & SecConst.USER_SENDNOTIFICATION) != // 0) ) if (log.isDebugEnabled()) { log.debug("Type does not contain SecConst.USER_SENDNOTIFICATION, no notification sent."); } } if (log.isTraceEnabled()) { log.trace("<sendNotification: user=" + data.getUsername() + ", email=" + useremail); } }
From source file:org.ejbca.core.ejb.ca.caadmin.CAAdminSessionBean.java
@Override public void renewCA(final AuthenticationToken authenticationToken, final int caid, final String nextSignKeyAlias, Date customNotBefore, final boolean createLinkCertificate) throws AuthorizationDeniedException, CryptoTokenOfflineException { if (log.isTraceEnabled()) { log.trace(">CAAdminSession, renewCA(), caid=" + caid); }//from w w w. j a va 2 s .c o m Collection<Certificate> cachain = null; Certificate cacertificate = null; // check authorization if (!accessSession.isAuthorizedNoLogging(authenticationToken, AccessRulesConstants.REGULAR_RENEWCA)) { final String detailsMsg = intres.getLocalizedMessage("caadmin.notauthorizedtorenew", Integer.valueOf(caid)); auditSession.log(EventTypes.ACCESS_CONTROL, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE, authenticationToken.toString(), String.valueOf(caid), null, null, detailsMsg); throw new AuthorizationDeniedException(detailsMsg); } // Get CA info. try { CA ca = caSession.getCAForEdit(authenticationToken, caid); if (ca.getStatus() == CAConstants.CA_OFFLINE || ca.getCAToken().getTokenStatus(true, cryptoTokenSession .getCryptoToken(ca.getCAToken().getCryptoTokenId())) == CryptoToken.STATUS_OFFLINE) { String msg = intres.getLocalizedMessage("error.catokenoffline", ca.getName()); throw new CryptoTokenOfflineException(msg); } if (ca.getSignedBy() == CAInfo.SIGNEDBYEXTERNALCA) { // We should never get here log.error("Directly renewing a CA signed by external can not be done"); throw new NotSupportedException("Directly renewing a CA signed by external can not be done"); } final CAToken caToken = ca.getCAToken(); final CryptoToken cryptoToken = cryptoTokenSession.getCryptoToken(caToken.getCryptoTokenId()); cryptoToken.testKeyPair(nextSignKeyAlias); caToken.setNextCertSignKey(nextSignKeyAlias); // Activate the next signing key(s) and generate audit log caToken.activateNextSignKey(); final Map<String, Object> details = new LinkedHashMap<String, Object>(); details.put("msg", intres.getLocalizedMessage("catoken.activatednextkey", caid)); details.put("certSignKey", caToken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN)); details.put("crlSignKey", caToken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CRLSIGN)); details.put("sequence", caToken.getKeySequence()); auditSession.log(EventTypes.CA_KEYACTIVATE, EventStatus.SUCCESS, ModuleTypes.CA, ServiceTypes.CORE, authenticationToken.toString(), String.valueOf(caid), null, null, details); // if issuer is insystem CA or selfsigned, then generate new certificate. log.info("Renewing CA using " + caToken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN)); final PublicKey caPublicKey = cryptoToken .getPublicKey(caToken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN)); ca.setCAToken(caToken); final CertificateProfile certprofile = certificateProfileSession .getCertificateProfile(ca.getCertificateProfileId()); mergeCertificatePoliciesFromCAAndProfile(ca.getCAInfo(), certprofile); if (ca.getSignedBy() == CAInfo.SELFSIGNED) { // create selfsigned certificate EndEntityInformation cainfodata = makeEndEntityInformation(ca.getCAInfo()); // get from CAtoken to make sure it is fresh String sequence = caToken.getKeySequence(); cacertificate = ca.generateCertificate(cryptoToken, cainfodata, caPublicKey, -1, customNotBefore, ca.getValidity(), certprofile, sequence); // Build Certificate Chain cachain = new ArrayList<Certificate>(); cachain.add(cacertificate); } else { // Resign with CA above. if (ca.getSignedBy() > CAInfo.SPECIALCAIDBORDER || ca.getSignedBy() < 0) { // Create CA signed by other internal CA. final CA signca = caSession.getCAForEdit(authenticationToken, Integer.valueOf(ca.getSignedBy())); // Check that the signer is valid assertSignerValidity(authenticationToken, signca); // Create cacertificate EndEntityInformation cainfodata = makeEndEntityInformation(ca.getCAInfo()); String sequence = caToken.getKeySequence(); // get from CAtoken to make sure it is fresh CryptoToken signCryptoToken = cryptoTokenSession .getCryptoToken(signca.getCAToken().getCryptoTokenId()); cacertificate = signca.generateCertificate(signCryptoToken, cainfodata, caPublicKey, -1, customNotBefore, ca.getValidity(), certprofile, sequence); // Build Certificate Chain Collection<Certificate> rootcachain = signca.getCertificateChain(); cachain = new ArrayList<Certificate>(); cachain.add(cacertificate); cachain.addAll(rootcachain); } } // Set statuses and expire time ca.setExpireTime(CertTools.getNotAfter(cacertificate)); ca.setStatus(CAConstants.CA_ACTIVE); // Set the new certificate chain that we have created above ca.setCertificateChain(cachain); ca.createOrRemoveLinkCertificate(cryptoToken, createLinkCertificate, certprofile); // We need to save all this, audit logging that the CA is changed caSession.editCA(authenticationToken, ca, true); // Publish the new CA certificate publishCACertificate(authenticationToken, cachain, ca.getCRLPublishers(), ca.getSubjectDN()); publishingCrlSession.forceCRL(authenticationToken, caid); publishingCrlSession.forceDeltaCRL(authenticationToken, caid); // Audit log final String detailsMsg = intres.getLocalizedMessage("caadmin.renewdca", Integer.valueOf(caid)); auditSession.log(EjbcaEventTypes.CA_RENEWED, EventStatus.SUCCESS, ModuleTypes.CA, ServiceTypes.CORE, authenticationToken.toString(), String.valueOf(caid), null, null, detailsMsg); } catch (CryptoTokenOfflineException e) { final String detailsMsg = intres.getLocalizedMessage("caadmin.errorrenewca", Integer.valueOf(caid)); auditSession.log(EjbcaEventTypes.CA_RENEWED, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE, authenticationToken.toString(), String.valueOf(caid), null, null, detailsMsg); throw e; } catch (Exception e) { final String detailsMsg = intres.getLocalizedMessage("caadmin.errorrenewca", Integer.valueOf(caid)); auditSession.log(EjbcaEventTypes.CA_RENEWED, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE, authenticationToken.toString(), String.valueOf(caid), null, null, detailsMsg); throw new EJBException(e); } if (log.isTraceEnabled()) { log.trace("<CAAdminSession, renewCA(), caid=" + caid); } }
From source file:org.gss_project.gss.server.ejb.ExternalAPIBean.java
private void postFileToSolr(CommonsHttpSolrServer solr, Long id) throws ObjectNotFoundException { try {/*from w w w. jav a 2s .com*/ FileHeader file = dao.getFileForIndexing(id); FileBody body = file.getCurrentBody(); String mime = body.getMimeType(); boolean multipart = true; if (!mime.equals("application/pdf") && !mime.equals("text/plain") && !mime.equals("text/html") && !mime.endsWith("msword") && !mime.endsWith("ms-excel") && !mime.endsWith("powerpoint") || (body.getFileSize() > getConfiguration().getLong("solrDocumentUploadLimitInKB") * 1024)) multipart = false; if (!multipart) sendMetaDataOnly(solr, file); else { ContentStreamUpdateRequest solrRequest = new ContentStreamUpdateRequest( getConfiguration().getString("solr.rich.update.path")); solrRequest.setParam("literal.id", file.getId().toString()); solrRequest.setParam("literal.name", file.getName()); for (FileTag t : file.getFileTags()) { solrRequest.getParams().add("literal.tag", t.getTag()); } for (Permission p : file.getPermissions()) { if (p.getRead()) { if (p.getUser() != null) solrRequest.getParams().add("literal.ureaders", p.getUser().getId().toString()); else if (p.getGroup() != null) solrRequest.getParams().add("literal.greaders", p.getGroup().getId().toString()); } } solrRequest.setParam("literal.owner", file.getOwner().getId().toString()); solrRequest.setParam("literal.public", String.valueOf(file.isReadForAll())); File fsFile = new File(body.getStoredFilePath()); solrRequest.addFile(fsFile); try { solr.request(solrRequest); } catch (SolrException e) { logger.warn("File " + id + " failed with SolrException: " + e.getLocalizedMessage() + ". Retrying without the file"); //Let 's try without the file sendMetaDataOnly(solr, file); } catch (NullPointerException e) { logger.warn("File " + id + " failed with NullPointerException: " + e.getLocalizedMessage() + ". Retrying without the file"); //Let 's try without the file sendMetaDataOnly(solr, file); } catch (SolrServerException e) { logger.warn("File " + id + " failed with SolrServerException: " + e.getLocalizedMessage() + ". Retrying without the file"); //Let 's try without the file sendMetaDataOnly(solr, file); } } } catch (MalformedURLException e) { throw new EJBException(e); } catch (SolrServerException e) { throw new EJBException(e); } catch (IOException e) { throw new EJBException(e); } }
From source file:org.ejbca.core.ejb.ca.caadmin.CAAdminSessionBean.java
@Override public void revokeCA(AuthenticationToken admin, int caid, int reason) throws CADoesntExistsException, AuthorizationDeniedException { // check authorization if (!accessSession.isAuthorizedNoLogging(admin, StandardRules.ROLE_ROOT.resource())) { final String detailsMsg = intres.getLocalizedMessage("caadmin.notauthorizedtorevoke", Integer.valueOf(caid)); auditSession.log(EventTypes.ACCESS_CONTROL, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE, admin.toString(), String.valueOf(caid), null, null, detailsMsg); throw new AuthorizationDeniedException(detailsMsg); }/*from www.ja v a 2 s. c om*/ // Get CA info. CA ca = caSession.getCAForEdit(admin, caid); try { // Revoke all issued CA certificates for this CA Collection<Certificate> cacerts = certificateStoreSession.findCertificatesBySubject(ca.getSubjectDN()); for (Certificate certificate : cacerts) { revocationSession.revokeCertificate(admin, certificate, ca.getCRLPublishers(), reason, ca.getSubjectDN()); } // Revoke all certificates issued by this CA. If this is a root CA the CA certificates will be included in this batch as well // but if this is a subCA these are only the "entity" certificates issued by this CA if (ca.getStatus() != CAConstants.CA_EXTERNAL) { certificateStoreSession.revokeAllCertByCA(admin, ca.getSubjectDN(), reason); Collection<Integer> caids = new ArrayList<Integer>(); caids.add(Integer.valueOf(ca.getCAId())); publishingCrlSession.createCRLs(admin, caids, 0); } ca.setRevocationReason(reason); ca.setRevocationDate(new Date()); if (ca.getStatus() != CAConstants.CA_EXTERNAL) { ca.setStatus(CAConstants.CA_REVOKED); } // Store new status, audit logging caSession.editCA(admin, ca, true); final String detailsMsg = intres.getLocalizedMessage("caadmin.revokedca", ca.getName(), Integer.valueOf(reason)); auditSession.log(EjbcaEventTypes.CA_REVOKED, EventStatus.SUCCESS, ModuleTypes.CA, ServiceTypes.CORE, admin.toString(), String.valueOf(caid), null, null, detailsMsg); } catch (Exception e) { final String detailsMsg = intres.getLocalizedMessage("caadmin.errorrevoke", ca.getName()); auditSession.log(EjbcaEventTypes.CA_REVOKED, EventStatus.SUCCESS, ModuleTypes.CA, ServiceTypes.CORE, admin.toString(), String.valueOf(caid), null, null, detailsMsg); throw new EJBException(e); } }
From source file:org.ejbca.core.ejb.ca.caadmin.CAAdminSessionBean.java
@Override public void importCAFromKeyStore(AuthenticationToken admin, String caname, byte[] p12file, String keystorepass, String privkeypass, String privateSignatureKeyAlias, String privateEncryptionKeyAlias) { try {/*from w w w .ja v a 2s. c om*/ // check authorization if (!accessSession.isAuthorizedNoLogging(admin, StandardRules.ROLE_ROOT.resource())) { String msg = intres.getLocalizedMessage("caadmin.notauthorizedtocreateca", caname); Map<String, Object> details = new LinkedHashMap<String, Object>(); details.put("msg", msg); auditSession.log(EventTypes.ACCESS_CONTROL, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE, admin.toString(), null, null, null, details); } // load keystore java.security.KeyStore keystore = KeyStore.getInstance("PKCS12", "BC"); keystore.load(new java.io.ByteArrayInputStream(p12file), keystorepass.toCharArray()); // Extract signature keys if (privateSignatureKeyAlias == null || !keystore.isKeyEntry(privateSignatureKeyAlias)) { throw new Exception("Alias \"" + privateSignatureKeyAlias + "\" not found."); } Certificate[] signatureCertChain = KeyTools.getCertChain(keystore, privateSignatureKeyAlias); if (signatureCertChain.length < 1) { String msg = "Cannot load certificate chain with alias " + privateSignatureKeyAlias; log.error(msg); throw new Exception(msg); } Certificate caSignatureCertificate = (Certificate) signatureCertChain[0]; PublicKey p12PublicSignatureKey = caSignatureCertificate.getPublicKey(); PrivateKey p12PrivateSignatureKey = null; p12PrivateSignatureKey = (PrivateKey) keystore.getKey(privateSignatureKeyAlias, privkeypass.toCharArray()); log.debug("ImportSignatureKeyAlgorithm=" + p12PrivateSignatureKey.getAlgorithm()); // Extract encryption keys PrivateKey p12PrivateEncryptionKey = null; PublicKey p12PublicEncryptionKey = null; Certificate caEncryptionCertificate = null; if (privateEncryptionKeyAlias != null) { if (!keystore.isKeyEntry(privateEncryptionKeyAlias)) { throw new Exception("Alias \"" + privateEncryptionKeyAlias + "\" not found."); } Certificate[] encryptionCertChain = KeyTools.getCertChain(keystore, privateEncryptionKeyAlias); if (encryptionCertChain.length < 1) { String msg = "Cannot load certificate chain with alias " + privateEncryptionKeyAlias; log.error(msg); throw new Exception(msg); } caEncryptionCertificate = (Certificate) encryptionCertChain[0]; p12PrivateEncryptionKey = (PrivateKey) keystore.getKey(privateEncryptionKeyAlias, privkeypass.toCharArray()); p12PublicEncryptionKey = caEncryptionCertificate.getPublicKey(); } importCAFromKeys(admin, caname, keystorepass, signatureCertChain, p12PublicSignatureKey, p12PrivateSignatureKey, p12PrivateEncryptionKey, p12PublicEncryptionKey); } catch (Exception e) { String detailsMsg = intres.getLocalizedMessage("caadmin.errorimportca", caname, "PKCS12", e.getMessage()); auditSession.log(EjbcaEventTypes.CA_IMPORT, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE, admin.toString(), null, null, null, detailsMsg); throw new EJBException(e); } }
From source file:org.ejbca.core.ejb.ca.caadmin.CAAdminSessionBean.java
@Override public void restoreCAKeyStore(AuthenticationToken authenticationToken, String caname, byte[] p12file, String keystorepass, String privkeypass, String privateSignatureKeyAlias, String privateEncryptionKeyAlias) { if (log.isTraceEnabled()) { log.trace(">restoreCAKeyStore"); }/* w w w .j a va2 s . c o m*/ try { // check authorization if (!accessSession.isAuthorizedNoLogging(authenticationToken, StandardRules.ROLE_ROOT.resource())) { final String detailsMsg = intres.getLocalizedMessage("caadmin.notauthorizedtorestorecatoken", caname); auditSession.log(EventTypes.ACCESS_CONTROL, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE, authenticationToken.toString(), null, null, null, detailsMsg); } CA thisCa = caSession.getCAForEdit(authenticationToken, caname); final CAToken thisCAToken = thisCa.getCAToken(); CryptoToken cryptoToken = cryptoTokenSession.getCryptoToken(thisCAToken.getCryptoTokenId()); if (cryptoToken != null) { throw new Exception("CA already has an existing CryptoToken reference: " + cryptoToken.getId()); } // load keystore from input KeyStore keystore = KeyStore.getInstance("PKCS12", "BC"); keystore.load(new ByteArrayInputStream(p12file), keystorepass.toCharArray()); // Extract signature keys if (privateSignatureKeyAlias == null || !keystore.isKeyEntry(privateSignatureKeyAlias)) { throw new Exception("Alias \"" + privateSignatureKeyAlias + "\" not found."); } Certificate[] signatureCertChain = KeyTools.getCertChain(keystore, privateSignatureKeyAlias); if (signatureCertChain.length < 1) { String msg = "Cannot load certificate chain with alias " + privateSignatureKeyAlias; log.error(msg); throw new Exception(msg); } Certificate caSignatureCertificate = (Certificate) signatureCertChain[0]; PublicKey p12PublicSignatureKey = caSignatureCertificate.getPublicKey(); PrivateKey p12PrivateSignatureKey = null; p12PrivateSignatureKey = (PrivateKey) keystore.getKey(privateSignatureKeyAlias, privkeypass.toCharArray()); // Extract encryption keys PrivateKey p12PrivateEncryptionKey = null; PublicKey p12PublicEncryptionKey = null; Certificate caEncryptionCertificate = null; if (privateEncryptionKeyAlias != null) { if (!keystore.isKeyEntry(privateEncryptionKeyAlias)) { throw new Exception("Alias \"" + privateEncryptionKeyAlias + "\" not found."); } Certificate[] encryptionCertChain = KeyTools.getCertChain(keystore, privateEncryptionKeyAlias); if (encryptionCertChain.length < 1) { String msg = "Cannot load certificate chain with alias " + privateEncryptionKeyAlias; log.error(msg); throw new Exception(msg); } caEncryptionCertificate = (Certificate) encryptionCertChain[0]; p12PrivateEncryptionKey = (PrivateKey) keystore.getKey(privateEncryptionKeyAlias, privkeypass.toCharArray()); p12PublicEncryptionKey = caEncryptionCertificate.getPublicKey(); } else { throw new Exception("Missing encryption key"); } // Sign something to see that we are restoring the right private signature key String testSigAlg = (String) AlgorithmTools .getSignatureAlgorithms(thisCa.getCACertificate().getPublicKey()).iterator().next(); if (testSigAlg == null) { testSigAlg = "SHA1WithRSA"; } // Sign with imported private key byte[] input = "Test data...".getBytes(); Signature signature = Signature.getInstance(testSigAlg, "BC"); signature.initSign(p12PrivateSignatureKey); signature.update(input); byte[] signed = signature.sign(); // Verify with public key from CA certificate signature = Signature.getInstance(testSigAlg, "BC"); signature.initVerify(thisCa.getCACertificate().getPublicKey()); signature.update(input); if (!signature.verify(signed)) { throw new Exception("Could not use private key for verification. Wrong p12-file for this CA?"); } // Import the keys and save to database CAToken catoken = importKeysToCAToken(authenticationToken, keystorepass, thisCAToken.getProperties(), p12PrivateSignatureKey, p12PublicSignatureKey, p12PrivateEncryptionKey, p12PublicEncryptionKey, signatureCertChain, thisCa.getCAId()); thisCa.setCAToken(catoken); // Finally save the CA caSession.editCA(authenticationToken, thisCa, true); // Log final String detailsMsg = intres.getLocalizedMessage("caadmin.restoredcakeystore", Integer.valueOf(thisCa.getCAId())); auditSession.log(EjbcaEventTypes.CA_RESTORETOKEN, EventStatus.SUCCESS, ModuleTypes.CA, ServiceTypes.CORE, authenticationToken.toString(), String.valueOf(thisCa.getCAId()), null, null, detailsMsg); } catch (Exception e) { final String detailsMsg = intres.getLocalizedMessage("caadmin.errorrestorecakeystore", caname, "PKCS12", e.getMessage()); auditSession.log(EjbcaEventTypes.CA_RESTORETOKEN, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE, authenticationToken.toString(), null, null, null, detailsMsg); throw new EJBException(e); } if (log.isTraceEnabled()) { log.trace("<restoreCAKeyStore"); } }
From source file:org.ejbca.core.ejb.ca.caadmin.CAAdminSessionBean.java
@Override public void importCAFromKeys(AuthenticationToken authenticationToken, String caname, String keystorepass, Certificate[] signatureCertChain, PublicKey p12PublicSignatureKey, PrivateKey p12PrivateSignatureKey, PrivateKey p12PrivateEncryptionKey, PublicKey p12PublicEncryptionKey) throws CryptoTokenAuthenticationFailedException, CryptoTokenOfflineException, IllegalCryptoTokenException, AuthorizationDeniedException, CAExistsException, CAOfflineException { // Transform into token int caId = StringTools.strip(CertTools.getSubjectDN(signatureCertChain[0])).hashCode(); // caid CAToken catoken = null;// ww w .ja va2 s. c om try { catoken = importKeysToCAToken(authenticationToken, keystorepass, null, p12PrivateSignatureKey, p12PublicSignatureKey, p12PrivateEncryptionKey, p12PublicEncryptionKey, signatureCertChain, caId); } catch (OperatorCreationException e) { log.error(e.getLocalizedMessage(), e); throw new EJBException(e); } log.debug("CA-Info: " + catoken.getSignatureAlgorithm() + " " + catoken.getEncryptionAlgorithm()); // Identify the key algorithms for extended CA services, OCSP, XKMS, CMS String keyAlgorithm = AlgorithmTools.getKeyAlgorithm(p12PublicSignatureKey); String keySpecification = AlgorithmTools.getKeySpecification(p12PublicSignatureKey); if (keyAlgorithm == null || keyAlgorithm == AlgorithmConstants.KEYALGORITHM_RSA) { keyAlgorithm = AlgorithmConstants.KEYALGORITHM_RSA; keySpecification = "2048"; } // Do the general import CA ca = importCA(authenticationToken, caname, keystorepass, signatureCertChain, catoken, keyAlgorithm, keySpecification); // Finally audit log String msg = intres.getLocalizedMessage("caadmin.importedca", caname, "PKCS12", ca.getStatus()); Map<String, Object> details = new LinkedHashMap<String, Object>(); details.put("msg", msg); auditSession.log(EjbcaEventTypes.CA_IMPORT, EventStatus.SUCCESS, ModuleTypes.CA, ServiceTypes.CORE, authenticationToken.toString(), String.valueOf(ca.getCAId()), null, null, details); }
From source file:org.ejbca.core.ejb.ca.caadmin.CAAdminSessionBean.java
@Override @TransactionAttribute(TransactionAttributeType.SUPPORTS) public byte[] exportCAKeyStore(AuthenticationToken admin, String caname, String keystorepass, String privkeypass, String privateSignatureKeyAlias, String privateEncryptionKeyAlias) { log.trace(">exportCAKeyStore"); try {//from w ww .ja v a 2 s. com final CA thisCa = caSession.getCAForEdit(admin, caname); // Make sure we are not trying to export a hard or invalid token CAToken thisCAToken = thisCa.getCAToken(); final CryptoToken cryptoToken = cryptoTokenSession.getCryptoToken(thisCAToken.getCryptoTokenId()); if (!(cryptoToken instanceof SoftCryptoToken)) { throw new IllegalCryptoTokenException("Cannot export anything but a soft token."); } // Do not allow export without password protection if (StringUtils.isEmpty(keystorepass) || StringUtils.isEmpty(privkeypass)) { throw new IllegalArgumentException("Cannot export a token without password protection."); } // Check authorization if (!accessSession.isAuthorizedNoLogging(admin, StandardRules.ROLE_ROOT.resource())) { String msg = intres.getLocalizedMessage("caadmin.notauthorizedtoexportcatoken", caname); Map<String, Object> details = new LinkedHashMap<String, Object>(); details.put("msg", msg); auditSession.log(EventTypes.ACCESS_CONTROL, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE, admin.toString(), String.valueOf(thisCa.getCAId()), null, null, details); throw new AuthorizationDeniedException(msg); } // Fetch keys final char[] password = keystorepass.toCharArray(); ((SoftCryptoToken) cryptoToken).checkPasswordBeforeExport(password); cryptoToken.activate(password); PrivateKey p12PrivateEncryptionKey = cryptoToken .getPrivateKey(thisCAToken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_KEYENCRYPT)); PublicKey p12PublicEncryptionKey = cryptoToken .getPublicKey(thisCAToken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_KEYENCRYPT)); PrivateKey p12PrivateCertSignKey = cryptoToken .getPrivateKey(thisCAToken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN)); PrivateKey p12PrivateCRLSignKey = cryptoToken .getPrivateKey(thisCAToken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CRLSIGN)); if (!p12PrivateCertSignKey.equals(p12PrivateCRLSignKey)) { throw new Exception("Assertion of equal signature keys failed."); } // Proceed with the export byte[] ret = null; String format = null; if (thisCa.getCAType() == CAInfo.CATYPE_CVC) { log.debug("Exporting private key with algorithm: " + p12PrivateCertSignKey.getAlgorithm() + " of format: " + p12PrivateCertSignKey.getFormat()); format = p12PrivateCertSignKey.getFormat(); ret = p12PrivateCertSignKey.getEncoded(); } else { log.debug("Exporting PKCS12 keystore"); format = "PKCS12"; KeyStore keystore = KeyStore.getInstance("PKCS12", "BC"); keystore.load(null, keystorepass.toCharArray()); // Load keys into keystore Certificate[] certificateChainSignature = (Certificate[]) thisCa.getCertificateChain() .toArray(new Certificate[0]); Certificate[] certificateChainEncryption = new Certificate[1]; // certificateChainSignature[0].getSigAlgName(), // generate dummy certificate for encryption key. certificateChainEncryption[0] = CertTools.genSelfCertForPurpose("CN=dummy2", 36500, null, p12PrivateEncryptionKey, p12PublicEncryptionKey, thisCAToken.getEncryptionAlgorithm(), true, X509KeyUsage.keyEncipherment, true); log.debug("Exporting with sigAlgorithm " + AlgorithmTools.getSignatureAlgorithm(certificateChainSignature[0]) + "encAlgorithm=" + thisCAToken.getEncryptionAlgorithm()); if (keystore.isKeyEntry(privateSignatureKeyAlias)) { throw new Exception("Key \"" + privateSignatureKeyAlias + "\"already exists in keystore."); } if (keystore.isKeyEntry(privateEncryptionKeyAlias)) { throw new Exception("Key \"" + privateEncryptionKeyAlias + "\"already exists in keystore."); } keystore.setKeyEntry(privateSignatureKeyAlias, p12PrivateCertSignKey, privkeypass.toCharArray(), certificateChainSignature); keystore.setKeyEntry(privateEncryptionKeyAlias, p12PrivateEncryptionKey, privkeypass.toCharArray(), certificateChainEncryption); // Return KeyStore as byte array and clean up ByteArrayOutputStream baos = new ByteArrayOutputStream(); keystore.store(baos, keystorepass.toCharArray()); if (keystore.isKeyEntry(privateSignatureKeyAlias)) { keystore.deleteEntry(privateSignatureKeyAlias); } if (keystore.isKeyEntry(privateEncryptionKeyAlias)) { keystore.deleteEntry(privateEncryptionKeyAlias); } ret = baos.toByteArray(); } String msg = intres.getLocalizedMessage("caadmin.exportedca", caname, format); Map<String, Object> details = new LinkedHashMap<String, Object>(); details.put("msg", msg); auditSession.log(EjbcaEventTypes.CA_EXPORTTOKEN, EventStatus.SUCCESS, ModuleTypes.CA, ServiceTypes.CORE, admin.toString(), String.valueOf(thisCa.getCAId()), null, null, details); log.trace("<exportCAKeyStore"); return ret; } catch (Exception e) { String msg = intres.getLocalizedMessage("caadmin.errorexportca", caname, "PKCS12", e.getMessage()); Map<String, Object> details = new LinkedHashMap<String, Object>(); details.put("msg", msg); auditSession.log(EjbcaEventTypes.CA_EXPORTTOKEN, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE, admin.toString(), null, null, null, details); throw new EJBException(e); } }
From source file:org.ejbca.core.ejb.ca.caadmin.CAAdminSessionBean.java
/** * Checks the signer validity given a CA object and throws an EJBException to the caller. * This should only be called from create and edit CA methods. * /* w w w . j a va 2 s . c o m*/ * @param admin administrator calling the method * @param signca a CA object of the signer to be checked * @throws EJBException embedding a CertificateExpiredException or a CertificateNotYetValidException if the certificate has expired or is not yet * valid */ private void assertSignerValidity(AuthenticationToken admin, CA signca) { // Check validity of signers certificate final Certificate signcert = (Certificate) signca.getCACertificate(); try { CertTools.checkValidity(signcert, new Date()); } catch (CertificateExpiredException ce) { // Signers Certificate has expired. String msg = intres.getLocalizedMessage("signsession.caexpired", signca.getSubjectDN()); Map<String, Object> details = new LinkedHashMap<String, Object>(); details.put("msg", msg); auditSession.log(EjbcaEventTypes.CA_VALIDITY, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE, admin.toString(), String.valueOf(signca.getCAId()), null, null, details); throw new EJBException(ce); } catch (CertificateNotYetValidException cve) { String msg = intres.getLocalizedMessage("signsession.canotyetvalid", signca.getSubjectDN()); Map<String, Object> details = new LinkedHashMap<String, Object>(); details.put("msg", msg); auditSession.log(EjbcaEventTypes.CA_VALIDITY, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE, admin.toString(), String.valueOf(signca.getCAId()), null, null, details); throw new EJBException(cve); } }
From source file:org.ejbca.core.ejb.ca.caadmin.CAAdminSessionBean.java
/** * Helper method that activates CA services and publisher their certificates, if the services are marked as active * /*from w ww .j a v a 2 s.c om*/ * @throws AuthorizationDeniedException */ private void activateAndPublishExternalCAServices(AuthenticationToken admin, Collection<ExtendedCAServiceInfo> extendedCAServiceInfos, CA ca) throws AuthorizationDeniedException { // activate External CA Services Iterator<ExtendedCAServiceInfo> iter = extendedCAServiceInfos.iterator(); while (iter.hasNext()) { ExtendedCAServiceInfo info = (ExtendedCAServiceInfo) iter.next(); ArrayList<Certificate> certificates = new ArrayList<Certificate>(); if (info instanceof XKMSCAServiceInfo) { try { final CryptoToken cryptoToken = cryptoTokenSession .getCryptoToken(ca.getCAToken().getCryptoTokenId()); ca.initExtendedService(cryptoToken, ExtendedCAServiceTypes.TYPE_XKMSEXTENDEDSERVICE, ca); final List<Certificate> certPath = ((XKMSCAServiceInfo) ca .getExtendedCAServiceInfo(ExtendedCAServiceTypes.TYPE_XKMSEXTENDEDSERVICE)) .getCertificatePath(); if (certPath != null) { certificates.add(certPath.get(0)); } } catch (Exception fe) { String msg = intres.getLocalizedMessage("caadmin.errorcreatecaservice", "XKMSCAService"); log.error(msg, fe); throw new EJBException(fe); } } if (info instanceof CmsCAServiceInfo) { try { final CryptoToken cryptoToken = cryptoTokenSession .getCryptoToken(ca.getCAToken().getCryptoTokenId()); ca.initExtendedService(cryptoToken, ExtendedCAServiceTypes.TYPE_CMSEXTENDEDSERVICE, ca); final List<Certificate> certPath = ((CmsCAServiceInfo) ca .getExtendedCAServiceInfo(ExtendedCAServiceTypes.TYPE_CMSEXTENDEDSERVICE)) .getCertificatePath(); if (certPath != null) { certificates.add(certPath.get(0)); } } catch (Exception fe) { String msg = intres.getLocalizedMessage("caadmin.errorcreatecaservice", "CMSCAService"); log.error(msg, fe); throw new EJBException(fe); } } // Always store the certificate. Only publish the extended service // certificate for active services. Collection<Integer> publishers = null; if (info.getStatus() == ExtendedCAServiceInfo.STATUS_ACTIVE) { publishers = ca.getCRLPublishers(); } if ((!certificates.isEmpty())) { publishCACertificate(admin, certificates, publishers, ca.getSubjectDN()); } } }