Package org.ejbca.core

Examples of org.ejbca.core.EjbcaException


  }

  private int getCAId(Admin admin, String cAName) throws EjbcaException {
    CAInfo info = caAdminSession.getCAInfo(admin,cAName);
    if(info == null){
      throw new EjbcaException("Error CA '" + cAName + "' doesn't exists.");
    }
    int retval = info.getCAId();
    return retval;
  }
View Full Code Here


        return AVAILABLESOFTTOKENIDS[i];
      }
    }
    int retval = hardTokenSession.getHardTokenProfileId(admin,tokenName);
    if(retval == 0){
      throw new EjbcaException("Error Token with name " + tokenName + " doesn't exists.");
    }
    return retval;
  }
View Full Code Here

     
      // Get KeyPair
      keyRecoverySession.unmarkUser(admin,submessage.getUsername());
      X509Certificate orgcert = (X509Certificate) certificateStoreSession.findCertificateByIssuerAndSerno(admin,CertTools.stringToBCDNString(submessage.getIssuerDN()), submessage.getCertificateSN());
      if(orgcert == null){
        throw new EjbcaException("Error in Key Recovery Request, couldn't find specified certificate");
      }
      if(!userAdminSession.prepareForKeyRecovery(admin, userdata.getUsername(), userdata.getEndEntityProfileId(), orgcert)){
        throw new EjbcaException("Error in Key Recovery Request, no keys saved for specified request");
      }
      KeyRecoveryData keyData = keyRecoverySession.keyRecovery(admin, submessage.getUsername(), userdata.getEndEntityProfileId());
      if(keyData == null){
        throw new EjbcaException("Error in Key Recovery Request, no keys saved for specified request");
      }     
      KeyPair savedKeys = keyData.getKeyPair();
     
      X509Certificate cert = null
      if(submessage.getReUseCertificate()){ 
View Full Code Here

  }

  private int getCertificateProfileId(Admin admin, String certificateProfileName) throws EjbcaException {   
    int retval = certificateProfileSession.getCertificateProfileId(admin,certificateProfileName);
    if(retval == 0){
      throw new EjbcaException("Error Certificate profile '" + certificateProfileName + "' doesn't exists.");
    }
    return retval;
  }
View Full Code Here

  }

  private int getEndEntityProfileId(Admin admin,String endEntityProfileName) throws EjbcaException {
    int retval = endEntityProfileSession.getEndEntityProfileId(admin,endEntityProfileName);
    if(retval == 0){
      throw new EjbcaException("Error End Entity profile '" + endEntityProfileName + "' doesn't exists.");
    }
    return retval;
  }
View Full Code Here

        }
      final String endEntityProfileName = endEntityProfileSession.getEndEntityProfileName(admin, endEntityProfileId);
        try {
            FieldValidator.validate(userDataVO, endEntityProfileId, endEntityProfileName);
        } catch (CustomFieldException e1) {
            throw new EjbcaException(ErrorCode.FIELD_VALUE_NOT_VALID, e1.getMessage(), e1);
        }
        final String dn = CertTools.stringToBCDNString(StringTools.strip(userDataVO.getDN()));
        if (log.isTraceEnabled()) {
            log.trace(">addUser(" + userDataVO.getUsername() + ", password, " + dn + ", " + userDataVO.getDN() + ", " + userDataVO.getSubjectAltName() + ", "
                    + userDataVO.getEmail() + ", profileId: " + endEntityProfileId + ")");
        }
        final String altName = StringTools.strip(userDataVO.getSubjectAltName());
        final String email = StringTools.strip(userDataVO.getEmail());
        userDataVO.setUsername(username);
        userDataVO.setDN(dn);
        userDataVO.setSubjectAltName(altName);
        userDataVO.setEmail(email);
        final int type = userDataVO.getType();
        String newpassword = userDataVO.getPassword();
        EndEntityProfile profile = null// Only look this up if we need it..
        if (userDataVO.getPassword() == null) {
          profile = endEntityProfileSession.getEndEntityProfile(admin, endEntityProfileId);
          if (profile.useAutoGeneratedPasswd()) {
                // special case used to signal regeneration of password
                newpassword = profile.getAutoGeneratedPasswd();
          }
        }
        if (globalConfiguration.getEnableEndEntityProfileLimitations()) {
          if (profile==null) {
            profile = endEntityProfileSession.getEndEntityProfile(admin, endEntityProfileId);
          }
            // Check if user fulfills it's profile.
            try {
              final String dirattrs = userDataVO.getExtendedinformation() != null ? userDataVO.getExtendedinformation().getSubjectDirectoryAttributes() : null;
                profile.doesUserFullfillEndEntityProfile(username, userDataVO.getPassword(), dn, altName, dirattrs,
                    email, userDataVO.getCertificateProfileId(), clearpwd,
                        (type & SecConst.USER_KEYRECOVERABLE) != 0, (type & SecConst.USER_SENDNOTIFICATION) != 0, userDataVO.getTokenType(), userDataVO
                                .getHardTokenIssuerId(), caid, userDataVO.getExtendedinformation());
            } catch (UserDoesntFullfillEndEntityProfile e) {
                final String msg = intres.getLocalizedMessage("ra.errorfullfillprofile", endEntityProfileName, dn, e.getMessage());
                logSession.log(admin, caid, LogConstants.MODULE_RA, new Date(), username, null, LogConstants.EVENT_ERROR_ADDEDENDENTITY, msg);
                throw e;
            }
        }
        // Get CAInfo, to be able to read configuration
        final CAInfo caInfo = caAdminSession.getCAInfoOrThrowException(admin, caid);
        // Check if approvals is required. (Only do this if store users, otherwise this approval is disabled.)
        if (caInfo.isUseUserStorage()) {
          final int numOfApprovalsRequired = getNumOfApprovalRequired(admin, CAInfo.REQ_APPROVAL_ADDEDITENDENTITY, caid, userDataVO.getCertificateProfileId());
          if (numOfApprovalsRequired > 0) {
              AddEndEntityApprovalRequest ar = new AddEndEntityApprovalRequest(userDataVO, clearpwd, admin, null, numOfApprovalsRequired, caid, endEntityProfileId);
              if (ApprovalExecutorUtil.requireApproval(ar, NONAPPROVABLECLASSNAMES_ADDUSER)) {
                approvalSession.addApprovalRequest(admin, ar, globalConfiguration);
                throw new WaitingForApprovalException(intres.getLocalizedMessage("ra.approvalad"));
              }
          }
        }
        // Check if the subjectDN serialnumber already exists.
        if (caInfo.isDoEnforceUniqueSubjectDNSerialnumber()) {
          if (caInfo.isUseUserStorage()) {
            if (!isSubjectDnSerialnumberUnique(caid, dn, username)) {
              throw new EjbcaException(ErrorCode.SUBJECTDN_SERIALNUMBER_ALREADY_EXISTS, "Error: SubjectDN Serialnumber already exists.");
            }
          } else {
            log.warn("CA configured to enforce unique SubjectDN serialnumber, but not to store any user data. Check will be ignored. Please verify your configuration.");
          }
        }
View Full Code Here

          assertAuthorizedToEndEntityProfile(admin, endEntityProfileId, AccessRulesConstants.EDIT_RIGHTS, caid, username, LogConstants.EVENT_INFO_CHANGEDENDENTITY);
        }
        try {
            FieldValidator.validate(userDataVO, endEntityProfileId, endEntityProfileSession.getEndEntityProfileName(admin, endEntityProfileId));
        } catch (CustomFieldException e) {
            throw new EjbcaException(ErrorCode.FIELD_VALUE_NOT_VALID, e.getMessage(), e);
        }
        String dn = CertTools.stringToBCDNString(StringTools.strip(userDataVO.getDN()));
        String altName = userDataVO.getSubjectAltName();
        if (log.isTraceEnabled()) {
            log.trace(">changeUser(" + username + ", " + dn + ", " + userDataVO.getEmail() + ")");
        }
        final UserData userData = UserData.findByUsername(entityManager, username);
        if (userData == null) {
            final String msg = intres.getLocalizedMessage("ra.erroreditentity", username);
            logSession.log(admin, caid, LogConstants.MODULE_RA, new Date(), username, null, LogConstants.EVENT_ERROR_CHANGEDENDENTITY, msg);
            log.error(msg);
            throw new EJBException(msg);
        }
        final EndEntityProfile profile = endEntityProfileSession.getEndEntityProfile(admin, endEntityProfileId);
        // if required, we merge the existing user dn into the dn provided by the web service.
        if (fromWebService && profile.getAllowMergeDnWebServices()) {
            if (userData != null) {
                if (userData.getSubjectDN() != null) {
                    final Map<String, String> dnMap = new HashMap<String, String>();
                    if (profile.getUse(DnComponents.DNEMAIL, 0)) {
                        dnMap.put(DnComponents.DNEMAIL, userDataVO.getEmail());
                    }
                    try {
                        dn = (new DistinguishedName(userData.getSubjectDN())).mergeDN(new DistinguishedName(dn), true, dnMap).toString();
                    } catch (InvalidNameException e) {
                        log.debug("Invalid dn. We make it empty");
                        dn = "";
                    }
                }
                if (userData.getSubjectAltName() != null) {
                    final Map<String, String> dnMap = new HashMap<String, String>();
                    if (profile.getUse(DnComponents.RFC822NAME, 0)) {
                        dnMap.put(DnComponents.RFC822NAME, userDataVO.getEmail());
                    }
                    try {
                        // SubjectAltName is not mandatory so
                        if (altName == null) {
                            altName = "";
                        }
                        altName = (new DistinguishedName(userData.getSubjectAltName())).mergeDN(new DistinguishedName(altName), true, dnMap).toString();
                    } catch (InvalidNameException e) {
                        log.debug("Invalid altName. We make it empty");
                        altName = "";
                    }
                }
            }
        }
        String newpassword = userDataVO.getPassword();
        if (profile.useAutoGeneratedPasswd() && newpassword != null) {
            // special case used to signal regeneraton of password
            newpassword = profile.getAutoGeneratedPasswd();
        }

        final int type = userDataVO.getType();
        final ExtendedInformation ei = userDataVO.getExtendedinformation();
        // Check if user fulfills it's profile.
        if (globalConfiguration.getEnableEndEntityProfileLimitations()) {
            try {
              String dirattrs = null;
              if (ei != null) {
                dirattrs = ei.getSubjectDirectoryAttributes();
              }
            // It is only meaningful to verify the password if we change it in some way, and if we are not autogenerating it
              if (!profile.useAutoGeneratedPasswd() && StringUtils.isNotEmpty(newpassword)) {
                  profile.doesUserFullfillEndEntityProfile(username, userDataVO.getPassword(), dn, altName, dirattrs, userDataVO.getEmail(),
                      userDataVO.getCertificateProfileId(), clearpwd, (type & SecConst.USER_KEYRECOVERABLE) != 0, (type & SecConst.USER_SENDNOTIFICATION) != 0,
                      userDataVO.getTokenType(), userDataVO.getHardTokenIssuerId(), caid, ei);
              } else {
                  profile.doesUserFullfillEndEntityProfileWithoutPassword(username, dn, altName, dirattrs, userDataVO.getEmail(),
                      userDataVO.getCertificateProfileId(), (type & SecConst.USER_KEYRECOVERABLE) != 0, (type & SecConst.USER_SENDNOTIFICATION) != 0,
                      userDataVO.getTokenType(), userDataVO.getHardTokenIssuerId(), caid, ei);
              }
            } catch (UserDoesntFullfillEndEntityProfile e) {
                final String msg = intres.getLocalizedMessage("ra.errorfullfillprofile", Integer.valueOf(endEntityProfileId), dn, e.getMessage());
                logSession.log(admin, caid, LogConstants.MODULE_RA, new Date(), username, null, LogConstants.EVENT_INFO_CHANGEDENDENTITY, msg);
                throw e;
            }
        }
        // Check if approvals is required.
        final int numOfApprovalsRequired = getNumOfApprovalRequired(admin, CAInfo.REQ_APPROVAL_ADDEDITENDENTITY, caid, userDataVO.getCertificateProfileId());
        if (numOfApprovalsRequired > 0) {
            final UserDataVO orguserdata = userData.toUserDataVO();
            final EditEndEntityApprovalRequest ar = new EditEndEntityApprovalRequest(userDataVO, clearpwd, orguserdata, admin, null, numOfApprovalsRequired, caid, endEntityProfileId);
            if (ApprovalExecutorUtil.requireApproval(ar, NONAPPROVABLECLASSNAMES_CHANGEUSER)) {
                approvalSession.addApprovalRequest(admin, ar, getGlobalConfiguration(admin));
                throw new WaitingForApprovalException(intres.getLocalizedMessage("ra.approvaledit"));
            }
        }
        // Check if the subjectDN serialnumber already exists.
        if (caAdminSession.getCAInfoOrThrowException(admin, caid).isDoEnforceUniqueSubjectDNSerialnumber()) {
            if (!isSubjectDnSerialnumberUnique(caid, dn, username)) {
              throw new EjbcaException(ErrorCode.SUBJECTDN_SERIALNUMBER_ALREADY_EXISTS, "Error: SubjectDN Serialnumber already exists.");
            }
        }
        try {
            userData.setDN(dn);
            userData.setSubjectAltName(altName);
View Full Code Here

        // Get CA info.
        CAData cadata = CAData.findById(entityManager, Integer.valueOf(caid));
        if (cadata == null) {
            String msg = intres.getLocalizedMessage("caadmin.errorcertresp", Integer.valueOf(caid));
            logSession.log(admin, caid, LogConstants.MODULE_CA, new java.util.Date(), null, null, LogConstants.EVENT_ERROR_CAEDITED, msg);
            throw new EjbcaException(msg);
        }
        try {
            CA ca = cadata.getCA();
            try {
                if (responsemessage instanceof X509ResponseMessage) {
                    cacert = ((X509ResponseMessage) responsemessage).getCertificate();
                } else {
                    String msg = intres.getLocalizedMessage("caadmin.errorcertrespillegalmsg", responsemessage != null ? responsemessage.getClass().getName()
                            : "null");
                    logSession.log(admin, caid, LogConstants.MODULE_CA, new java.util.Date(), null, null, LogConstants.EVENT_ERROR_CAEDITED, msg);
                    throw new EjbcaException(msg);
                }

                // If signed by external CA, process the received certificate
                // and store it, activating the CA
                if (ca.getSignedBy() == CAInfo.SIGNEDBYEXTERNALCA) {
                    // Check that CA DN is equal to the certificate response.
                    if (!CertTools.getSubjectDN(cacert).equals(CertTools.stringToBCDNString(ca.getSubjectDN()))) {
                        String msg = intres.getLocalizedMessage("caadmin.errorcertrespwrongdn", CertTools.getSubjectDN(cacert), ca.getSubjectDN());
                        logSession.log(admin, caid, LogConstants.MODULE_CA, new java.util.Date(), null, null, LogConstants.EVENT_ERROR_CAEDITED, msg);
                        throw new EjbcaException(msg);
                    }

                    ArrayList<Certificate> tmpchain = new ArrayList<Certificate>();
                    tmpchain.add(cacert);
                    // If we have a chain given as parameter, we will use that.
                    // If no parameter is given we assume that the request chain
                    // was stored when the request was created.
                    Collection<Certificate> reqchain = null;
                    if ((cachain != null) && (cachain.size() > 0)) {
                        reqchain = CertTools.createCertChain(cachain);
                        log.debug("Using CA certificate chain from parameter of size: " + reqchain.size());
                    } else {
                        reqchain = ca.getRequestCertificateChain();
                        log.debug("Using pre-stored CA certificate chain.");
                        if (reqchain == null) {
                            String msg = intres.getLocalizedMessage("caadmin.errornorequestchain", caid, ca.getSubjectDN());
                            log.info(msg);
                            throw new CertPathValidatorException(msg);
                        }
                    }
                    log.debug("Picked up request certificate chain of size: " + reqchain.size());
                    tmpchain.addAll(reqchain);
                    Collection<Certificate> chain = CertTools.createCertChain(tmpchain);
                    log.debug("Storing certificate chain of size: " + chain.size());
                    // Before importing the certificate we want to make sure
                    // that the public key matches the CAs private key
                    CATokenContainer catoken = ca.getCAToken();
                    // If it is a DV certificate signed by a CVCA, enrich the
                    // public key for EC parameters from the CVCA's certificate
                    PublicKey pk = cacert.getPublicKey();
                    if (StringUtils.equals(cacert.getType(), "CVC")) {
                        if (pk.getAlgorithm().equals("ECDSA")) {
                            CardVerifiableCertificate cvccert = (CardVerifiableCertificate) cacert;
                            try {
                                if ((cvccert.getCVCertificate().getCertificateBody().getAuthorizationTemplate().getAuthorizationField().getRole() == AuthorizationRoleEnum.DV_D)
                                        || (cvccert.getCVCertificate().getCertificateBody().getAuthorizationTemplate().getAuthorizationField().getRole() == AuthorizationRoleEnum.DV_F)) {
                                    log.debug("Enriching DV public key with EC parameters from CVCA");
                                    Certificate cvcacert = (Certificate) reqchain.iterator().next();
                                    pk = KeyTools.getECPublicKeyWithParams(pk, cvcacert.getPublicKey());
                                }
                            } catch (InvalidKeySpecException e) {
                                log.debug("Strange CVCA certificate that we can't get the key from, continuing anyway...", e);
                            } catch (NoSuchFieldException e) {
                                log.debug("Strange DV certificate with no AutheorizationRole, continuing anyway...", e);
                            }
                        } else {
                            log.debug("Key is not ECDSA, don't try to enrich with EC parameters.");
                        }
                    } else {
                        log.debug("Cert is not CVC, no need to enrich with EC parameters.");
                    }
                    try {
                        KeyTools.testKey(catoken.getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN), pk, catoken.getProvider());
                    } catch (Exception e1) {
                        log.debug("The received certificate response does not match the CAs private signing key for purpose CAKEYPURPOSE_CERTSIGN, trying CAKEYPURPOSE_CERTSIGN_NEXT...");
                        if (e1 instanceof InvalidKeyException) {
                            log.trace(e1);
                        } else {
                            // If it's not invalid key, we want to see more of
                            // the error
                            log.debug("Error: ", e1);
                        }
                        try {
                            KeyTools.testKey(catoken.getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN_NEXT), pk, catoken.getProvider());
                            // This was OK, so we must also activate the next
                            // signing key when importing this certificate
                            catoken.activateNextSignKey(tokenAuthenticationCode);
                            ca.setCAToken(catoken);
                            // In order to generate a certificate with this
                            // keystore we must make sure it is activated
                            ca.getCAToken().activate(tokenAuthenticationCode);
                        } catch (Exception e2) {
                            log.debug("The received certificate response does not match the CAs private signing key for purpose CAKEYPURPOSE_CERTSIGN_NEXT either, giving up.");
                            if ((e2 instanceof InvalidKeyException) || (e2 instanceof IllegalArgumentException)) {
                                log.trace(e2);
                            } else {
                                // If it's not invalid key or missing authentication code,
                                // we want to see more of the error
                                log.debug("Error: ", e2);
                            }
                            throw new EjbcaException(ErrorCode.INVALID_KEY, e2);
                        }
                    }
                    ca.setCertificateChain(chain);

                    // Publish CA Certificate
                    publishCACertificate(admin, chain, ca.getCRLPublishers(), ca.getSubjectDN());

                    // Set status to active, so we can sign certificates for the
                    // external services below.
                    cadata.setStatus(SecConst.CA_ACTIVE);
                    ca.setStatus(SecConst.CA_ACTIVE);

                    // activate External CA Services
                    Iterator<Integer> iter = ca.getExternalCAServiceTypes().iterator();
                    while (iter.hasNext()) {
                        int type = iter.next().intValue();
                        try {
                            ca.initExternalService(type, ca);
                            ArrayList<Certificate> extcacertificate = new ArrayList<Certificate>();
                            ExtendedCAServiceInfo info = null;
                            if (type == ExtendedCAServiceInfo.TYPE_OCSPEXTENDEDSERVICE) {
                                info = (OCSPCAServiceInfo) ca.getExtendedCAServiceInfo(ExtendedCAServiceInfo.TYPE_OCSPEXTENDEDSERVICE);
                                // The OCSP certificate is the same as the
                                // singing certificate
                            }
                            if (type == ExtendedCAServiceInfo.TYPE_XKMSEXTENDEDSERVICE) {
                                info = ca.getExtendedCAServiceInfo(ExtendedCAServiceInfo.TYPE_XKMSEXTENDEDSERVICE);
                                extcacertificate.add(((XKMSCAServiceInfo) info).getXKMSSignerCertificatePath().get(0));
                            }
                            if (type == ExtendedCAServiceInfo.TYPE_CMSEXTENDEDSERVICE) {
                                info = ca.getExtendedCAServiceInfo(ExtendedCAServiceInfo.TYPE_CMSEXTENDEDSERVICE);
                                extcacertificate.add(((CmsCAServiceInfo) info).getCertificatePath().get(0));
                            }
                            // Publish the extended service certificate, but
                            // only for active services
                            if ((info != null) && (info.getStatus() == ExtendedCAServiceInfo.STATUS_ACTIVE) && (!extcacertificate.isEmpty())) {
                                publishCACertificate(admin, extcacertificate, ca.getCRLPublishers(), ca.getSubjectDN());
                            }
                        } catch (CATokenOfflineException e) {
                            String msg = intres.getLocalizedMessage("caadmin.errorcreatecaservice", Integer.valueOf(caid));
                            logSession.log(admin, admin.getCaId(), LogConstants.MODULE_CA, new java.util.Date(), null, null,
                                    LogConstants.EVENT_ERROR_CACREATED, msg, e);
                            throw e;
                        } catch (Exception fe) {
                            String msg = intres.getLocalizedMessage("caadmin.errorcreatecaservice", Integer.valueOf(caid));
                            logSession.log(admin, admin.getCaId(), LogConstants.MODULE_CA, new java.util.Date(), null, null,
                                    LogConstants.EVENT_ERROR_CACREATED, msg, fe);
                            throw new EJBException(fe);
                        }
                    }

                    // Set expire time
                    ca.setExpireTime(CertTools.getNotAfter(cacert));
                    cadata.setExpireTime(CertTools.getNotAfter(cacert).getTime());
                    // Save CA
                    cadata.setCA(ca);

                    // Create initial CRL
                    crlCreateSession.createCRLs(admin, ca, ca.getCAInfo());
                } else {
                    String msg = intres.getLocalizedMessage("caadmin.errorcreatecaservice", Integer.valueOf(caid));
                    // Cannot create certificate request for internal CA
                    logSession.log(admin, caid, LogConstants.MODULE_CA, new java.util.Date(), null, null, LogConstants.EVENT_ERROR_CAEDITED, msg);
                    throw new EjbcaException(msg);
                }

            } catch (CATokenOfflineException e) {
                String msg = intres.getLocalizedMessage("caadmin.errorcertresp", Integer.valueOf(caid));
                logSession.log(admin, caid, LogConstants.MODULE_CA, new java.util.Date(), null, null, LogConstants.EVENT_ERROR_CAEDITED, msg, e);
                throw e;
            } catch (CertificateEncodingException e) {
                String msg = intres.getLocalizedMessage("caadmin.errorcertresp", Integer.valueOf(caid));
                logSession.log(admin, caid, LogConstants.MODULE_CA, new java.util.Date(), null, null, LogConstants.EVENT_ERROR_CAEDITED, msg, e);
                throw new EjbcaException(e.getMessage());
            } catch (CertificateException e) {
                String msg = intres.getLocalizedMessage("caadmin.errorcertresp", Integer.valueOf(caid));
                logSession.log(admin, caid, LogConstants.MODULE_CA, new java.util.Date(), null, null, LogConstants.EVENT_ERROR_CAEDITED, msg, e);
                throw new EjbcaException(e.getMessage());
            } catch (IOException e) {
                String msg = intres.getLocalizedMessage("caadmin.errorcertresp", Integer.valueOf(caid));
                logSession.log(admin, caid, LogConstants.MODULE_CA, new java.util.Date(), null, null, LogConstants.EVENT_ERROR_CAEDITED, msg, e);
                throw new EjbcaException(e.getMessage());
            } catch (InvalidAlgorithmParameterException e) {
                String msg = intres.getLocalizedMessage("caadmin.errorcertresp", Integer.valueOf(caid));
                logSession.log(admin, caid, LogConstants.MODULE_CA, new java.util.Date(), null, null, LogConstants.EVENT_ERROR_CAEDITED, msg, e);
                throw new EjbcaException(e.getMessage());
            } catch (NoSuchAlgorithmException e) {
                String msg = intres.getLocalizedMessage("caadmin.errorcertresp", Integer.valueOf(caid));
                logSession.log(admin, caid, LogConstants.MODULE_CA, new java.util.Date(), null, null, LogConstants.EVENT_ERROR_CAEDITED, msg, e);
                throw new EjbcaException(e.getMessage());
            } catch (NoSuchProviderException e) {
                String msg = intres.getLocalizedMessage("caadmin.errorcertresp", Integer.valueOf(caid));
                logSession.log(admin, caid, LogConstants.MODULE_CA, new java.util.Date(), null, null, LogConstants.EVENT_ERROR_CAEDITED, msg, e);
                throw new EjbcaException(e.getMessage());
            }
        } catch (UnsupportedEncodingException e) {
            String msg = intres.getLocalizedMessage("caadmin.errorcertresp", Integer.valueOf(caid));
            logSession.log(admin, caid, LogConstants.MODULE_CA, new java.util.Date(), null, null, LogConstants.EVENT_ERROR_CAEDITED, msg, e);
            throw new EjbcaException(e.getMessage());
        }

        String msg = intres.getLocalizedMessage("caadmin.certrespreceived", Integer.valueOf(caid));
        logSession.log(admin, caid, LogConstants.MODULE_CA, new java.util.Date(), null, null, LogConstants.EVENT_INFO_CAEDITED, msg);
    }
View Full Code Here

        }
        if (caid >= 0 && caid <= CAInfo.SPECIALCAIDBORDER) {
          // This should never happen.
          String msg = intres.getLocalizedMessage("caadmin.errordeactivatetoken", Integer.valueOf(caid));
          logSession.log(admin, caid, LogConstants.MODULE_CA, new java.util.Date(), null, null, LogConstants.EVENT_ERROR_CAEDITED, msg);
          throw new EjbcaException(msg);
        }
        CAData cadata = CAData.findById(entityManager, Integer.valueOf(caid));
        if (cadata == null) {
          String msg = intres.getLocalizedMessage("caadmin.errorcanotfound", Integer.valueOf(caid));
          logSession.log(admin, caid, LogConstants.MODULE_CA, new java.util.Date(), null, null, LogConstants.EVENT_ERROR_CAEDITED, msg);
          throw new EJBException(msg);
        }
        if (cadata.getStatus() == SecConst.CA_EXTERNAL) {
          String msg = intres.getLocalizedMessage("caadmin.catokenexternal", Integer.valueOf(caid));
          log.info(msg);
          return;
        } else if (cadata.getStatus() == SecConst.CA_ACTIVE) {
          try {
            cadata.getCA().getCAToken().deactivate();
            cadata.setStatus(SecConst.CA_OFFLINE);
            // Invalidate CA cache to refresh information
            CACacheManager.instance().removeCA(cadata.getCaId().intValue());
            String msg = intres.getLocalizedMessage("caadmin.catokendeactivated", cadata.getName());
            logSession.log(admin, caid, LogConstants.MODULE_CA, new java.util.Date(), null, null, LogConstants.EVENT_INFO_CAEDITED, msg);
          } catch (Exception e) {
            throw new EJBException(e);
          }
        } else {
          String msg = intres.getLocalizedMessage("caadmin.errornotonline", cadata.getName());
          logSession.log(admin, caid, LogConstants.MODULE_CA, new java.util.Date(), null, null, LogConstants.EVENT_ERROR_CAEDITED, msg);
          throw new EjbcaException(msg);
        }
    }
View Full Code Here

              if (ca.isUseCertificateStorage()) {
                final Set<String> users = certificateStoreSession.findUsernamesByIssuerDNAndSubjectDN(admin, caSubjectDN, data.getDN());
                if ( users.size()>0 && !users.contains(username) ) {
                  String msg = intres.getLocalizedMessage("signsession.subjectdn_exists_for_another_user", "'"+username+"'", listUsers(users));
                  log.info(msg);
                  throw new EjbcaException(ErrorCode.CERTIFICATE_WITH_THIS_SUBJECTDN_ALLREADY_EXISTS_FOR_ANOTHER_USER, msg);
                }
              } else {
                log.warn("CA configured to enforce unique SubjectDN, but not to store issued certificates. Check will be ignored. Please verify your configuration.");
              }
            }
            if ( ca.isDoEnforceUniquePublicKeys() ){
              if (ca.isUseCertificateStorage()) {
                final Set<String> users = certificateStoreSession.findUsernamesByIssuerDNAndSubjectKeyId(admin, caSubjectDN, KeyTools.createSubjectKeyId(pk).getKeyIdentifier());
                if ( users.size()>0 && !users.contains(username) ) {
                  String msg = intres.getLocalizedMessage("signsession.key_exists_for_another_user", "'"+username+"'", listUsers(users));
                  log.info(msg);
                  throw new EjbcaException(ErrorCode.CERTIFICATE_FOR_THIS_KEY_ALLREADY_EXISTS_FOR_ANOTHER_USER, msg);
                }
              } else {
                log.warn("CA configured to enforce unique entity keys, but not to store issued certificates. Check will be ignored. Please verify your configuration.");
              }
            }
            // Retrieve the certificate profile this user should have
      final int certProfileId;
      final CertificateProfile certProfile;
      {
        final int tmpCertProfileId = data.getCertificateProfileId();
        final CertificateProfile tmpCertProfile = certificateProfileSession.getCertificateProfile(admin, tmpCertProfileId);
        // What if certProfile == null?
        if (tmpCertProfile != null) {
          certProfileId = tmpCertProfileId;
          certProfile = tmpCertProfile;
        } else {
          certProfileId = SecConst.CERTPROFILE_FIXED_ENDUSER;
          certProfile = certificateProfileSession.getCertificateProfile(admin, certProfileId);
        }
      }
          if (log.isDebugEnabled()) {
            log.debug("Using certificate profile with id " + certProfileId);
          }
            // Check that CAid is among available CAs
            boolean caauthorized = false;
            for (final Integer nextInt : certProfile.getAvailableCAs()) {
                final int next = nextInt.intValue();
                if (next == caid || next == CertificateProfile.ANYCA) {
                    caauthorized = true;
                    break;
                }
            }
            if (!caauthorized) {
                String msg = intres.getLocalizedMessage("signsession.errorcertprofilenotauthorized", Integer.valueOf(caid), Integer.valueOf(certProfile.getType()));
                logSession.log(admin, caid, LogConstants.MODULE_CA, new Date(), username, null, LogConstants.EVENT_ERROR_CREATECERTIFICATE, msg);
                throw new EJBException(msg);
            }

            // Sign Session bean is only able to issue certificates with a End Entity or SubCA type certificate profile.
            if ( (certProfile.getType() != CertificateProfile.TYPE_ENDENTITY) && (certProfile.getType() != CertificateProfile.TYPE_SUBCA) ) {
                String msg = intres.getLocalizedMessage("signsession.errorcertprofiletype", Integer.valueOf(certProfile.getType()));
                logSession.log(admin, caid, LogConstants.MODULE_CA, new Date(), username, null, LogConstants.EVENT_ERROR_CREATECERTIFICATE, msg);
                throw new EJBException(msg);
            }

            int keyLength = KeyTools.getKeyLength(pk);
          if (log.isDebugEnabled()) {
            log.debug("Keylength = " + keyLength);
          }
            if (keyLength == -1) {
                String text = intres.getLocalizedMessage("signsession.unsupportedkeytype", pk.getClass().getName());
                logSession.log(admin, caid, LogConstants.MODULE_CA, new Date(), username, null, LogConstants.EVENT_INFO_CREATECERTIFICATE, text);
                throw new IllegalKeyException(text);
            }
            if ((keyLength < (certProfile.getMinimumAvailableBitLength() - 1))
                    || (keyLength > (certProfile.getMaximumAvailableBitLength()))) {
                String text = intres.getLocalizedMessage("signsession.illegalkeylength", Integer.valueOf(keyLength));
                logSession.log(admin, caid, LogConstants.MODULE_CA, new Date(), username, null, LogConstants.EVENT_INFO_CREATECERTIFICATE, text);
                throw new IllegalKeyException(text);
            }

            // Below we have a small loop if it would happen that we generate the same serial number twice
      Exception storeEx = null; // this will not be null if stored == false after the below passage
            Certificate cert = null;
            String cafingerprint = null;
            String serialNo = "unknown";
      final long updateTime = new Date().getTime();
            String tag = null;
      final boolean useCustomSN;
      {
        final ExtendedInformation ei = data.getExtendedinformation();
        useCustomSN = ei!=null && ei.certificateSerialNumber()!=null;
      }
      final int maxRetrys;
      if ( useCustomSN ) {
        if (ca.isUseCertificateStorage() && !signSession.isUniqueCertificateSerialNumberIndex()) {
          final String msg = intres.getLocalizedMessage("signsession.not_unique_certserialnumberindex");
          log.error(msg);
          throw new NoUniqueCertSerialNumberIndexException(new EjbcaException(msg));
        }
        if ( !certProfile.getAllowCertSerialNumberOverride() ) {
          final String msg = intres.getLocalizedMessage("signsession.certprof_not_allowing_cert_sn_override", Integer.valueOf(certProfileId));
          log.info(msg);
          throw new NoUniqueCertSerialNumberIndexException(new EjbcaException(msg));
        }
        maxRetrys = 1;
      } else {
        maxRetrys = 5;
      }
            for ( int retrycounter=0; retrycounter<maxRetrys; retrycounter++ ) {
                cert = ca.generateCertificate(data, requestX509Name, pk, keyusage, notBefore, notAfter, certProfile, extensions, sequence);
                serialNo = CertTools.getSerialNumberAsString(cert);
                cafingerprint = CertTools.getFingerprintAsString(cacert);
                // Store certificate in the database, if this CA is configured to do so.
                if (!ca.isUseCertificateStorage()) {
                  break// We have our cert and we don't need to store it.. Move on..
                }
                try {
                    certificateStoreSession.storeCertificate(admin, cert, username, cafingerprint, SecConst.CERT_ACTIVE, certProfile.getType(), certProfileId, tag, updateTime);                       
          storeEx = null;
          break;
                } catch (Exception e) {
                    // If we have created a unique index on (issuerDN,serialNumber) on table CertificateData we can
                    // get a CreateException here if we would happen to generate a certificate with the same serialNumber
                    // as one already existing certificate.
          if ( retrycounter+1<maxRetrys ) {
            log.info("Can not store certificate with serNo ("+serialNo+"), will retry (retrycounter="+retrycounter+") with a new certificate with new serialNo: "+e.getMessage());
          }
                    storeEx = e;
                }
            }
      if ( storeEx!=null ) {
        if ( useCustomSN ) {
          final String msg = intres.getLocalizedMessage("signsession.cert_serial_number_allready_in_database", serialNo);
          log.info(msg);
          throw new NoUniqueCertSerialNumberIndexException(new EjbcaException(msg));
        }
        log.error("Can not store certificate in database in 5 tries, aborting: ", storeEx);
        throw storeEx;
      }
View Full Code Here

TOP

Related Classes of org.ejbca.core.EjbcaException

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.