Package org.ejbca.core.model.ra

Examples of org.ejbca.core.model.ra.UserDataVO


  protected void isAuthorizedToRepublish(Admin admin, String username, int caid) throws AuthorizationDeniedException, EjbcaException {
    try {
      if(!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.REGULAR_VIEWCERTIFICATE)) {
          Authorizer.throwAuthorizationException(admin, AccessRulesConstants.REGULAR_VIEWCERTIFICATE, null);
      }
      UserDataVO userdata = userAdminSession.findUser(admin, username);
      if(userdata == null){
        String msg = intres.getLocalizedMessage("ra.errorentitynotexist", username);             
        throw new EjbcaException(ErrorCode.USER_NOT_FOUND, msg);
      }
      if(!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.ENDENTITYPROFILEPREFIX + userdata.getEndEntityProfileId() + AccessRulesConstants.VIEW_RIGHTS)) {
          Authorizer.throwAuthorizationException(admin, AccessRulesConstants.ENDENTITYPROFILEPREFIX + userdata.getEndEntityProfileId() + AccessRulesConstants.VIEW_RIGHTS, null);
      }
      if(!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.CAPREFIX + caid )){
          Authorizer.throwAuthorizationException(admin, AccessRulesConstants.CAPREFIX + caid, null);
      }
View Full Code Here


  protected void isAuthorizedToHardTokenData(Admin admin, String username, boolean viewPUKData) throws AuthorizationDeniedException, EjbcaException {
    try {
      if(!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.REGULAR_VIEWHARDTOKENS)) {
          Authorizer.throwAuthorizationException(admin, AccessRulesConstants.REGULAR_VIEWHARDTOKENS, null);
      }
      UserDataVO userdata = userAdminSession.findUser(admin, username);
      if(userdata == null){
        String msg = intres.getLocalizedMessage("ra.errorentitynotexist", username);             
        throw new EjbcaException(ErrorCode.USER_NOT_FOUND, msg);
      }

      if(!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.REGULAR_VIEWHARDTOKENS)) {
          Authorizer.throwAuthorizationException(admin, AccessRulesConstants.REGULAR_VIEWHARDTOKENS, null);
      }
      if(viewPUKData){
        if(!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.REGULAR_VIEWPUKS)) {
            Authorizer.throwAuthorizationException(admin, AccessRulesConstants.REGULAR_VIEWPUKS, null);
        }
      }

      if(userdata != null){
          if(!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.ENDENTITYPROFILEPREFIX + userdata.getEndEntityProfileId() + AccessRulesConstants.HARDTOKEN_RIGHTS)) {
              Authorizer.throwAuthorizationException(admin, AccessRulesConstants.ENDENTITYPROFILEPREFIX + userdata.getEndEntityProfileId() + AccessRulesConstants.HARDTOKEN_RIGHTS, null);
          }
        if(viewPUKData){
            if(!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.ENDENTITYPROFILEPREFIX + userdata.getEndEntityProfileId() + AccessRulesConstants.HARDTOKEN_PUKDATA_RIGHTS)) { 
                Authorizer.throwAuthorizationException(admin, AccessRulesConstants.ENDENTITYPROFILEPREFIX + userdata.getEndEntityProfileId() + AccessRulesConstants.HARDTOKEN_PUKDATA_RIGHTS, null);
            }
        }
      }

    } catch (EJBException e) {
View Full Code Here

                }
              }
        }
        }

        final UserDataVO userdatavo = new UserDataVO(userdata.getUsername(),
            userdata.getSubjectDN(),
        caid,
        userdata.getSubjectAltName(),
        userdata.getEmail(),
        userdata.getStatus(),
        userdata.getType(),
        endentityprofileid,
        certificateprofileid,
        null,
        null,
        tokenid,
        hardtokenissuerid,
        useEI ? ei : null);
   
    userdatavo.setPassword(userdata.getPassword());
   
    return userdatavo;
  }
View Full Code Here

        final IPatternLogger logger = TransactionLogger.getPatternLogger();
        try {
          final EjbcaWSHelper ejbhelper = new EjbcaWSHelper(wsContext, authorizationSession, caAdminSession, certificateProfileSession, certificateStoreSession, endEntityProfileSession, hardTokenSession, userAdminSession);
          final Admin admin = ejbhelper.getAdmin();
          logAdminName(admin,logger);
          final UserDataVO userdatavo = ejbhelper.convertUserDataVOWS(admin, userdata);
            if (userAdminSession.existsUser(admin, userdatavo.getUsername())) {
              if (log.isDebugEnabled()) {
                log.debug("User " + userdata.getUsername() + " exists, update the userdata. New status of user '"+userdata.getStatus()+"'." );         
              }
              userAdminSession.changeUser(admin,userdatavo,userdata.isClearPwd(), true);
            } else {
View Full Code Here

    // get and old status that we can remember so we can reset status if this fails in the last step
    int olduserStatus = UserDataConstants.STATUS_GENERATED;
        final IPatternLogger logger = TransactionLogger.getPatternLogger();
        logAdminName(admin,logger);
        try {
       UserDataVO user = userAdminSession.findUser(admin, username);
      // See if this user already exists.
      // We allow renewal of certificates for IS's that are not revoked
      // In that case look for it's last old certificate and try to authenticate the request using an outer signature.
      // If this verification is correct, set status to NEW and continue process the request.
      if (user != null) {
        olduserStatus = user.getStatus();
        // If user is revoked, we can not proceed
        if ( (olduserStatus == UserDataConstants.STATUS_REVOKED) || (olduserStatus == UserDataConstants.STATUS_HISTORICAL) ) {
          throw new AuthorizationDeniedException("User '"+username+"' is revoked.");
        }
        CVCObject parsedObject = CertificateParser.parseCVCObject(Base64.decode(cvcreq.getBytes()));
        if (parsedObject instanceof CVCAuthenticatedRequest) {
          log.debug("Received an authenticated request, could be an initial DV request signed by CVCA or a renewal for DV or IS.");
          CVCAuthenticatedRequest authreq = (CVCAuthenticatedRequest)parsedObject;
          CVCPublicKey cvcKey = authreq.getRequest().getCertificateBody().getPublicKey();
          String algorithm = AlgorithmUtil.getAlgorithmName(cvcKey.getObjectIdentifier());
          log.debug("Received request has a public key with algorithm: "+algorithm);
          HolderReferenceField holderRef = authreq.getRequest().getCertificateBody().getHolderReference();
          CAReferenceField caRef = authreq.getAuthorityReference();

          // Check to see that the inner signature does not also verify using an old certificate
          // because that means the same keys were used, and that is not allowed according to the EU policy
          // This must be done whether it is signed by CVCA or a renewal request
          Collection<java.security.cert.Certificate> oldcerts = certificateStoreSession.findCertificatesByUsername(admin, username);
          if (oldcerts != null) {
            log.debug("Found "+oldcerts.size()+" old certificates for user "+username);
            Iterator<java.security.cert.Certificate> iterator = oldcerts.iterator();
            while (iterator.hasNext()) {
              java.security.cert.Certificate cert = iterator.next();
              PublicKey pk = getCVPublicKey(admin, cert);
              CVCertificate innerreq = authreq.getRequest();
              checkInnerCollision(pk, innerreq, holderRef.getConcatenated()); // Throws AuthorizationDeniedException
            }
          }

          boolean verifiedOuter = false; // So we can throw an error if we could not verify
          if (StringUtils.equals(holderRef.getMnemonic(), caRef.getMnemonic()) && StringUtils.equals(holderRef.getCountry(), caRef.getCountry())) {
            log.debug("Authenticated request is self signed, we will try to verify it using user's old certificate.");
            Collection<java.security.cert.Certificate> certs = certificateStoreSession.findCertificatesByUsername(admin, username);
            // certs contains certificates ordered with last expire date first. Last expire date should be last issued cert
            // We have to iterate over available user certificates, because we don't know which on signed the old one
            // and cv certificates have very coarse grained validity periods so we can't really know which one is the latest one
            // if 2 certificates are issued the same day.
            if (certs != null) {
              log.debug("Found "+certs.size()+" old certificates for user "+username);
              Iterator<java.security.cert.Certificate> iterator = certs.iterator();
              while (iterator.hasNext()) {
                java.security.cert.Certificate cert = iterator.next();
                try {
                  // Only allow renewal if the old certificate is valid
                  PublicKey pk = getCVPublicKey(admin, cert);
                  if (log.isDebugEnabled()) {
                    log.debug("Trying to verify the outer signature with an old certificate, fp: "+CertTools.getFingerprintAsString(cert));                   
                  }
                  authreq.verify(pk);
                  log.debug("Verified outer signature");
                  // Yes we did it, we can move on to the next step because the outer signature was actually created with some old certificate
                  verifiedOuter = true;
                  if (ejbhelper.checkValidityAndSetUserPassword(admin, cert, username, password)) {
                    // If we managed to verify the certificate we will break out of the loop                 
                    break;
                  }
                 
                  // If verification of outer signature fails because the signature is invalid we will break and deny the request...with a message
                } catch (InvalidKeyException e) {
                  String msg = intres.getLocalizedMessage("cvc.error.outersignature", holderRef.getConcatenated(), e.getMessage());             
                  log.warn(msg, e);
                } catch (CertificateExpiredException e) { // thrown by checkValidityAndSetUserPassword
                  String msg = intres.getLocalizedMessage("cvc.error.outersignature", holderRef.getConcatenated(), e.getMessage());             
                  // Only log this with DEBUG since it will be a common case that happens, nothing that should cause any alerts
                  log.debug(msg);
                  // This exception we want to throw on, because we want to give this error if there was a certificate suitable for
                  // verification, but it had expired. This is thrown by checkValidityAndSetUserPassword after the request has already been
                  // verified using the public key of the certificate.
                  throw e;
                } catch (CertificateException e) {
                  String msg = intres.getLocalizedMessage("cvc.error.outersignature", holderRef.getConcatenated(), e.getMessage());             
                  log.warn(msg, e);
                } catch (NoSuchAlgorithmException e) {
                  String msg = intres.getLocalizedMessage("cvc.error.outersignature", holderRef.getConcatenated(), e.getMessage());             
                  log.info(msg, e);
                } catch (NoSuchProviderException e) {
                  String msg = intres.getLocalizedMessage("cvc.error.outersignature", holderRef.getConcatenated(), e.getMessage());             
                  log.warn(msg, e);
                } catch (SignatureException e) {
                  // Failing to verify the outer signature will be normal, since we must try all old certificates
                  if (log.isDebugEnabled()) {
                    String msg = intres.getLocalizedMessage("cvc.error.outersignature", holderRef.getConcatenated(), e.getMessage());             
                    log.debug(msg);                 
                  }
                }
              } // while (iterator.hasNext()) {
              // if verification failed because the old cert was not yet valid, continue processing as usual, using the sent in username/password hoping the
              // status is NEW and password is correct. If old certificate was expired a CertificateExpiredException is thrown above.

            } // if (certs != null) {
           
            // If there are no old certificate, continue processing as usual, using the sent in username/password hoping the
            // status is NEW and password is correct.
          } else { // if (StringUtils.equals(holderRef, caRef))
            // Subject and issuerDN is CN=Mnemonic,C=Country
            String dn = "CN="+caRef.getMnemonic()+",C="+caRef.getCountry();
            log.debug("Authenticated request is not self signed, we will try to verify it using a CVCA certificate: "+dn);
            CAInfo info = caAdminSession.getCAInfoOrThrowException(admin, CertTools.stringToBCDNString(dn).hashCode());
            if (info != null) {
              Collection<java.security.cert.Certificate> certs = info.getCertificateChain();
              if (certs != null) {
                log.debug("Found "+certs.size()+" certificates in chain for CA with DN: "+dn);             
                Iterator<java.security.cert.Certificate> iterator = certs.iterator();
                if (iterator.hasNext()) {
                  // The CA certificate is first in chain
                  java.security.cert.Certificate cert = iterator.next();
                  if (log.isDebugEnabled()) {
                    log.debug("Trying to verify the outer signature with a CVCA certificate, fp: "+CertTools.getFingerprintAsString(cert));                   
                  }
                  try {
                    // The CVCA certificate always contains the full key parameters, no need to du any EC curve parameter magic here
                    authreq.verify(cert.getPublicKey());
                    log.debug("Verified outer signature");
                    verifiedOuter = true;
                    // Yes we did it, we can move on to the next step because the outer signature was actually created with some old certificate
                    if (!ejbhelper.checkValidityAndSetUserPassword(admin, cert, username, password)) {
                      // If the CA certificate was not valid, we are not happy                 
                      String msg = intres.getLocalizedMessage("cvc.error.outersignature", holderRef.getConcatenated(), "CA certificate not valid for CA: "+info.getCAId());             
                      log.info(msg);
                      throw new AuthorizationDeniedException(msg);
                    }             
                  } catch (InvalidKeyException e) {
                    String msg = intres.getLocalizedMessage("cvc.error.outersignature", holderRef.getConcatenated(), e.getMessage());             
                    log.warn(msg, e);
                  } catch (CertificateException e) {
                    String msg = intres.getLocalizedMessage("cvc.error.outersignature", holderRef.getConcatenated(), e.getMessage());             
                    log.warn(msg, e);
                  } catch (NoSuchAlgorithmException e) {
                    String msg = intres.getLocalizedMessage("cvc.error.outersignature", holderRef.getConcatenated(), e.getMessage());             
                    log.warn(msg, e);
                  } catch (NoSuchProviderException e) {
                    String msg = intres.getLocalizedMessage("cvc.error.outersignature", holderRef.getConcatenated(), e.getMessage());             
                    log.warn(msg, e);
                  } catch (SignatureException e) {
                    String msg = intres.getLocalizedMessage("cvc.error.outersignature", holderRef.getConcatenated(), e.getMessage());             
                    log.warn(msg, e);
                  }             
                }               
              } else {
                log.info("No CA certificate found to authenticate request: "+dn);
              }
            } else {
              log.info("No CA found to authenticate request: "+dn);
            }
          }
          // if verification failed because we could not verify the outer signature at all it is an error
          if (!verifiedOuter) {
            String msg = intres.getLocalizedMessage("cvc.error.outersignature", holderRef.getConcatenated(), "No certificate found that could authenticate request");             
            log.info(msg);
            throw new AuthorizationDeniedException(msg);
          }
        } // if (parsedObject instanceof CVCAuthenticatedRequest)
        // If it is not an authenticated request, with an outer signature, continue processing as usual,
        // using the sent in username/password hoping the status is NEW and password is correct.
      } else {
        // If there are no old user, continue processing as usual... it will fail
        log.debug("No existing user with username: "+username);
      }
     
      // Finally generate the certificate (assuming status is NEW and password is correct
      byte[] response = processCertReq(username, password, cvcreq, REQTYPE_CVC, null, CertificateHelper.RESPONSETYPE_CERTIFICATE, logger);
      CertificateResponse ret = new CertificateResponse(CertificateHelper.RESPONSETYPE_CERTIFICATE, response);
      byte[] b64cert = ret.getData();
      CVCertificate certObject = CertificateParser.parseCertificate(Base64.decode(b64cert));
      java.security.cert.Certificate iscert = new CardVerifiableCertificate(certObject);
      ArrayList<Certificate> retval = new ArrayList<Certificate>();
      retval.add(new Certificate((java.security.cert.Certificate)iscert));
      // Get the certificate chain
      if (user != null) {
        int caid = user.getCAId();
        caAdminSession.verifyExistenceOfCA(caid);
        Collection<java.security.cert.Certificate> certs = signSession.getCertificateChain(admin, caid);
        Iterator<java.security.cert.Certificate> iter = certs.iterator();
        while (iter.hasNext()) {
          java.security.cert.Certificate cert = iter.next();
View Full Code Here

    try {
      final EjbcaWSHelper ejbhelper = new EjbcaWSHelper(wsContext, authorizationSession, caAdminSession, certificateProfileSession, certificateStoreSession, endEntityProfileSession, hardTokenSession, userAdminSession);
      final Admin admin = ejbhelper.getAdmin();       
            logAdminName(admin,logger);
      // check authorization to CAID
      final UserDataVO userdata = userAdminSession.findUser(admin, username);
      if (userdata == null) {
        throw new NotFoundException(intres.getLocalizedMessage("ra.errorentitynotexist", username));
      }
      final int caid = userdata.getCAId();
      caAdminSession.verifyExistenceOfCA(caid);
      if (!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.CAPREFIX +caid)) {
          Authorizer.throwAuthorizationException(admin, AccessRulesConstants.CAPREFIX +caid, null);
      }
      if (!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.REGULAR_CREATECERTIFICATE)) {
          Authorizer.throwAuthorizationException(admin, AccessRulesConstants.REGULAR_CREATECERTIFICATE, null);
      }
      // Check tokentype
      if (userdata.getTokenType() != SecConst.TOKEN_SOFT_BROWSERGEN) {
        throw EjbcaWSHelper.getEjbcaException("Error: Wrong Token Type of user, must be 'USERGENERATED' for PKCS10/SPKAC/CRMF/CVC requests",
                                        logger, ErrorCode.BAD_USER_TOKEN_TYPE, null);
      }

      IRequestMessage imsg = null;
View Full Code Here

        EjbcaWSHelper ejbhelper = new EjbcaWSHelper(wsContext, authorizationSession, caAdminSession, certificateProfileSession, certificateStoreSession, endEntityProfileSession, hardTokenSession, userAdminSession);
        Admin admin = ejbhelper.getAdmin();
              logAdminName(admin,logger);

        // check CAID
        UserDataVO userdata = userAdminSession.findUser(admin,username);
        if(userdata == null){
          String msg = intres.getLocalizedMessage("ra.errorentitynotexist", username);             
          throw new NotFoundException(msg);
        }
        int caid = userdata.getCAId();
        caAdminSession.verifyExistenceOfCA(caid);
        if(!authorizationSession.isAuthorized(admin, AccessRulesConstants.CAPREFIX +caid)) {
            Authorizer.throwAuthorizationException(admin, AccessRulesConstants.CAPREFIX +caid, null);
        }

        if(!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.REGULAR_CREATECERTIFICATE)) {
            Authorizer.throwAuthorizationException(admin, AccessRulesConstants.REGULAR_CREATECERTIFICATE, null);
        }
       
        // Check tokentype
        if(userdata.getTokenType() != SecConst.TOKEN_SOFT_P12){
                  throw EjbcaWSHelper.getEjbcaException("Error: Wrong Token Type of user, must be 'P12' for PKCS12 requests", logger, ErrorCode.BAD_USER_TOKEN_TYPE, null);
        }

        boolean usekeyrecovery = globalConfigurationSession.getCachedGlobalConfiguration(admin).getEnableKeyRecovery();
        log.debug("usekeyrecovery: "+usekeyrecovery);
        boolean savekeys = userdata.getKeyRecoverable() && usekeyrecovery &&  (userdata.getStatus() != UserDataConstants.STATUS_KEYRECOVERY);
        log.debug("userdata.getKeyRecoverable(): "+userdata.getKeyRecoverable());
        log.debug("userdata.getStatus(): "+userdata.getStatus());
        log.debug("savekeys: "+savekeys);
        boolean loadkeys = (userdata.getStatus() == UserDataConstants.STATUS_KEYRECOVERY) && usekeyrecovery;
        log.debug("loadkeys: "+loadkeys);
        int endEntityProfileId = userdata.getEndEntityProfileId();
        EndEntityProfile endEntityProfile = endEntityProfileSession.getEndEntityProfile(admin, endEntityProfileId);
        boolean reusecertificate = endEntityProfile.getReUseKeyRecoveredCertificate();
        log.debug("reusecertificate: "+reusecertificate);

        try {
View Full Code Here

      EjbcaWSHelper ejbhelper = new EjbcaWSHelper(wsContext, authorizationSession, caAdminSession, certificateProfileSession, certificateStoreSession, endEntityProfileSession, hardTokenSession, userAdminSession);
      Admin admin = ejbhelper.getAdmin();
            logAdminName(admin,logger);

      // check username
      UserDataVO userdata = userAdminSession.findUser(admin,username);
      if(userdata == null){
        String msg = intres.getLocalizedMessage("ra.errorentitynotexist", username);             
        throw new NotFoundException(msg);
      }
      // Check caid
      int caid = userdata.getCAId();
      caAdminSession.verifyExistenceOfCA(caid);
      if(!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.CAPREFIX +caid)) {
          Authorizer.throwAuthorizationException(admin, AccessRulesConstants.CAPREFIX +caid, null);
      }
      if (deleteUser) {
View Full Code Here

            boolean usekeyrecovery = globalConfigurationSession.getCachedGlobalConfiguration(admin).getEnableKeyRecovery()
            if(!usekeyrecovery){
        throw EjbcaWSHelper.getEjbcaException("Keyrecovery have to be enabled in the system configuration in order to use this command.",
                                        logger, ErrorCode.KEY_RECOVERY_NOT_AVAILABLE, null);
            }  
      UserDataVO userdata = userAdminSession.findUser(admin, username);
      if(userdata == null){
        String msg = intres.getLocalizedMessage("ra.errorentitynotexist", username);             
        throw new NotFoundException(msg);
      }
      if(keyRecoverySession.isUserMarked(admin, username)){
        // User is already marked for recovery.
        return;                    
      }
      // check CAID
      int caid = userdata.getCAId();
      caAdminSession.verifyExistenceOfCA(caid);
            if (!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.CAPREFIX + caid)) {
                Authorizer.throwAuthorizationException(admin, AccessRulesConstants.CAPREFIX + caid, null);
            }

      // Do the work, mark user for key recovery
      userAdminSession.prepareForKeyRecovery(admin, userdata.getUsername(), userdata.getEndEntityProfileId(), null);
        } catch (RuntimeException e) {  // EJBException, ...
            throw EjbcaWSHelper.getInternalException(e, logger);
        } finally {
            logger.writeln();
            logger.flush();
View Full Code Here

    if(significantcAInfo == null){
      throw EjbcaWSHelper.getEjbcaException("Error the given CA : " + userDataWS.getCaName() + " couldn't be found.",
          logger, ErrorCode.CA_NOT_EXISTS, null);
    }
   
      UserDataVO userDataVO = userAdminSession.findUser(intAdmin, userDataWS.getUsername());
      if(userDataVO != null){
        endEntityProfileId = userDataVO.getEndEntityProfileId();
        userExists = true;
      }else{
        endEntityProfileId = endEntityProfileSession.getEndEntityProfileId(intAdmin, userDataWS.getEndEntityProfileName());         
        if(endEntityProfileId == 0){
          throw EjbcaWSHelper.getEjbcaException("Error given end entity profile : " + userDataWS.getEndEntityProfileName() +" couldn't be found",
            logger, ErrorCode.EE_PROFILE_NOT_EXISTS, null);
        }
      }
     
     
      if(ejbhelper.isAdmin()){     
       
                if (!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.REGULAR_CREATECERTIFICATE)) {
                    Authorizer.throwAuthorizationException(admin, AccessRulesConstants.REGULAR_CREATECERTIFICATE, null);
                }
                if (!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.HARDTOKEN_ISSUEHARDTOKENS)) {
                    Authorizer.throwAuthorizationException(admin, AccessRulesConstants.HARDTOKEN_ISSUEHARDTOKENS, null);
                }
                if (!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.CAPREFIX + significantcAInfo.getCAId())) {
                    throw new AuthorizationDeniedException("Admin " + admin + " was not authorized to resource " + AccessRulesConstants.CAPREFIX
                            + significantcAInfo.getCAId());
                }
                if (userExists) {
                    if (!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.REGULAR_EDITENDENTITY)) {
                        Authorizer.throwAuthorizationException(admin, AccessRulesConstants.REGULAR_EDITENDENTITY, null);
                    }
                    endEntityProfileId = userDataVO.getEndEntityProfileId();
                    if (!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.ENDENTITYPROFILEPREFIX + endEntityProfileId
                            + AccessRulesConstants.EDIT_RIGHTS)) {
                        Authorizer.throwAuthorizationException(admin, AccessRulesConstants.ENDENTITYPROFILEPREFIX + endEntityProfileId
                                + AccessRulesConstants.EDIT_RIGHTS, null);
                    }

                    if (overwriteExistingSN) {
                        if (!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.REGULAR_REVOKEENDENTITY)) {
                            Authorizer.throwAuthorizationException(admin, AccessRulesConstants.REGULAR_REVOKEENDENTITY, null);
                        }
                        if (!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.ENDENTITYPROFILEPREFIX + endEntityProfileId
                                + AccessRulesConstants.REVOKE_RIGHTS)) {
                            Authorizer.throwAuthorizationException(admin, AccessRulesConstants.ENDENTITYPROFILEPREFIX + endEntityProfileId
                                    + AccessRulesConstants.REVOKE_RIGHTS, null);
                        }
                    }
                } else {
                    if (!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.REGULAR_CREATEENDENTITY)) {
                        Authorizer.throwAuthorizationException(admin, AccessRulesConstants.REGULAR_CREATEENDENTITY, null);
                    }
                    if (!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.ENDENTITYPROFILEPREFIX + endEntityProfileId
                            + AccessRulesConstants.CREATE_RIGHTS)) {
                        Authorizer.throwAuthorizationException(admin, AccessRulesConstants.ENDENTITYPROFILEPREFIX + endEntityProfileId
                                + AccessRulesConstants.CREATE_RIGHTS, null);
                    }
                    if (overwriteExistingSN) {
                        if (!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.REGULAR_REVOKEENDENTITY)) {
                            Authorizer.throwAuthorizationException(admin, AccessRulesConstants.REGULAR_REVOKEENDENTITY, null);
                        }
                        if (!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.ENDENTITYPROFILEPREFIX + endEntityProfileId
                                + AccessRulesConstants.REVOKE_RIGHTS)) {
                            Authorizer.throwAuthorizationException(admin, AccessRulesConstants.ENDENTITYPROFILEPREFIX + endEntityProfileId
                                    + AccessRulesConstants.REVOKE_RIGHTS, null);
                        }
                    }
                }

      }else{
        if(WebServiceConfiguration.getApprovalForGenTokenCertificates()){
          ar = new GenerateTokenApprovalRequest(userDataWS.getUsername(), userDataWS.getSubjectDN(), hardTokenDataWS.getLabel(),admin,null,WebServiceConfiguration.getNumberOfRequiredApprovals(),significantcAInfo.getCAId(),endEntityProfileId);
          int status = ApprovalDataVO.STATUS_REJECTED;          
          try{
            status = approvalSession.isApproved(admin, ar.generateApprovalId(), 1);
            approvalSuccessfullStep1 =  status == ApprovalDataVO.STATUS_APPROVED;
            if(approvalSuccessfullStep1){
              ApprovalDataVO approvalDataVO = approvalSession.findNonExpiredApprovalRequest(intAdmin, ar.generateApprovalId());
              String originalDN = ((GenerateTokenApprovalRequest) approvalDataVO.getApprovalRequest()).getDN();
              userDataWS.setSubjectDN(originalDN); // replace requested DN with original DN to make sure nothing have changed.
            }
            isRejectedStep1 = status == ApprovalDataVO.STATUS_REJECTED;
            if(   status == ApprovalDataVO.STATUS_EXPIREDANDNOTIFIED
               || status == ApprovalDataVO.STATUS_EXPIRED){
              throw new ApprovalException("");
            }
          }catch(ApprovalException e){
            approvalSession.addApprovalRequest(admin, ar, globalConfigurationSession.getCachedGlobalConfiguration(admin));
            throw new WaitingForApprovalException("Approval request with id " + ar.generateApprovalId() + " have been added for approval.",ar.generateApprovalId());
          }
        }else{
          throw new AuthorizationDeniedException();
        }
      }

    if(ar != null && isRejectedStep1){
      throw new ApprovalRequestExecutionException("The approval for id " + ar.generateApprovalId() + " have been rejected.");
    }
   
    if(ar != null && !approvalSuccessfullStep1){
      throw new WaitingForApprovalException("The approval for id " + ar.generateApprovalId() + " have not yet been approved", ar.generateApprovalId());
    }
   
    if(ar != null){
      admin = new ApprovedActionAdmin(admin.getAdminInformation().getX509Certificate(), admin.getUsername(), admin.getEmail());
    }
   
      hardTokenExists = hardTokenSession.existsHardToken(admin, hardTokenDataWS.getHardTokenSN());
      if(hardTokenExists){
        if(overwriteExistingSN){
          // fetch all old certificates and revoke them.
          Collection<java.security.cert.Certificate> currentCertificates = hardTokenSession.findCertificatesInHardToken(admin, hardTokenDataWS.getHardTokenSN());
          HardTokenData currentHardToken = hardTokenSession.getHardToken(admin, hardTokenDataWS.getHardTokenSN(), false);
          Iterator<java.security.cert.Certificate> iter = currentCertificates.iterator();
          while(iter.hasNext()){
            java.security.cert.X509Certificate nextCert = (java.security.cert.X509Certificate) iter.next();
            try {
              userAdminSession.revokeCert(admin, CertTools.getSerialNumber(nextCert), CertTools.getIssuerDN(nextCert), RevokedCertInfo.REVOCATION_REASON_SUPERSEDED);
            } catch (AlreadyRevokedException e) {
              // Ignore previously revoked certificates
            } catch (FinderException e) {
                            throw EjbcaWSHelper.getEjbcaException("Error revoking old certificate, the user : " + currentHardToken.getUsername() + " of the old certificate couldn't be found in database.",
                                                    logger, ErrorCode.USER_NOT_FOUND, null);
            }
          }

        }else{
          throw new HardTokenExistsException("Error hard token with sn " + hardTokenDataWS.getHardTokenSN() + " already exists.");
        }

      }


      if(revokePreviousCards){
        List<HardTokenDataWS> htd = getHardTokenDatas(admin,userDataWS.getUsername(), false, true, logger);
        Iterator<HardTokenDataWS> htdIter = htd.iterator();

        while(htdIter.hasNext()) {
          HardTokenDataWS toRevoke = htdIter.next();
          try{
              if(hardTokenDataWS.getLabel().equals(HardTokenConstants.LABEL_TEMPORARYCARD) && toRevoke.getLabel() != null && !toRevoke.getLabel().equals(HardTokenConstants.LABEL_TEMPORARYCARD)){

                // Token have extended key usage MS Logon, don't revoke it
                Iterator<java.security.cert.Certificate> revokeCerts = hardTokenSession.findCertificatesInHardToken(admin, toRevoke.getHardTokenSN()).iterator();

                while(revokeCerts.hasNext()){
                  X509Certificate next = (X509Certificate) revokeCerts.next();              
                  try{
                    if(WebServiceConfiguration.getSuspendAllCertificates() || next.getExtendedKeyUsage() == null || !next.getExtendedKeyUsage().contains(KeyPurposeId.id_kp_smartcardlogon.getId())){
                      userAdminSession.revokeCert(admin,next.getSerialNumber(), CertTools.getIssuerDN(next), RevokedCertInfo.REVOCATION_REASON_CERTIFICATEHOLD);
                    }
                  }catch(CertificateParsingException e){
                    log.error(e);
                  } catch (FinderException e) {
                    log.error(e);
                 
                }
           

            }else{
              revokeToken(admin, toRevoke.getHardTokenSN(), RevokedCertInfo.REVOCATION_REASON_UNSPECIFIED, logger);
            }
          }catch(AlreadyRevokedException e){
            // Do nothing
          }
        }
      }
   
    try{
      // Check if the userdata exist and edit/add it depending on which
      String password = PasswordGeneratorFactory.getInstance(PasswordGeneratorFactory.PASSWORDTYPE_ALLPRINTABLE).getNewPassword(8, 8);
      UserDataVO userData = ejbhelper.convertUserDataVOWS(admin, userDataWS);
      userData.setPassword(password);
      if(userExists){
        userAdminSession.changeUser(admin, userData, true);
      }else{
        userAdminSession.addUser(admin, userData, true);
      }

      Date bDate = new Date(System.currentTimeMillis() - (10 * 60 * 1000));
     
      Iterator<TokenCertificateRequestWS> iter = tokenRequests.iterator();
      while(iter.hasNext()){
        TokenCertificateRequestWS next = iter.next();

        int certificateProfileId = certificateProfileSession.getCertificateProfileId(admin, next.getCertificateProfileName());
        if(certificateProfileId == 0){
                    EjbcaWSHelper.getEjbcaException("Error the given Certificate Profile : " + next.getCertificateProfileName() + " couldn't be found.",
                                      logger, ErrorCode.CERT_PROFILE_NOT_EXISTS, null);
        }
       
        Date eDate = null;
       
        if(next.getValidityIdDays() != null ){
          try{
            long validity = Long.parseLong(next.getValidityIdDays());
            eDate = new Date(System.currentTimeMillis() + (validity  * 3600 *24 * 1000));
          }catch (NumberFormatException e){
                        EjbcaWSHelper.getEjbcaException("Error : Validity in Days must be a number",
                                          logger, ErrorCode.BAD_VALIDITY_FORMAT, null);
          }
        }
       
        CAInfo cAInfo = caAdminSession.getCAInfo(admin, next.getCAName());
        if(cAInfo == null){
          throw EjbcaWSHelper.getEjbcaException("Error the given CA : " + next.getCAName() + " couldn't be found.",
            logger, ErrorCode.CA_NOT_EXISTS, null);
        }

        if(!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.CAPREFIX + cAInfo.getCAId())) {
            Authorizer.throwAuthorizationException(admin, AccessRulesConstants.CAPREFIX + cAInfo.getCAId(), null);
        }
        if(next.getType() == HardTokenConstants.REQUESTTYPE_PKCS10_REQUEST){           
          userData.setCertificateProfileId(certificateProfileId);
          userData.setCAId(cAInfo.getCAId());
          userData.setPassword(password);
          userData.setStatus(UserDataConstants.STATUS_NEW);
          userAdminSession.changeUser(admin, userData, false);
          PKCS10RequestMessage pkcs10req = new PKCS10RequestMessage(next.getPkcs10Data());
          java.security.cert.Certificate cert;
          if(eDate == null){
              cert =  signSession.createCertificate(admin,userData.getUsername(),password, pkcs10req.getRequestPublicKey());
          }else{
            cert =  signSession.createCertificate(admin,userData.getUsername(),password, pkcs10req.getRequestPublicKey(), -1, bDate, eDate);
          }
         
          genCertificates.add(cert);
          retval.add(new TokenCertificateResponseWS(new Certificate(cert)));
        }else
          if(next.getType() == HardTokenConstants.REQUESTTYPE_KEYSTORE_REQUEST){

            if(!next.getTokenType().equals(HardTokenConstants.TOKENTYPE_PKCS12)){
              throw EjbcaWSHelper.getEjbcaException("Unsupported Key Store Type : " + next.getTokenType() + " only " + HardTokenConstants.TOKENTYPE_PKCS12 + " is supported",
                                                        logger, ErrorCode.NOT_SUPPORTED_KEY_STORE, null);
            }
            KeyPair keys = KeyTools.genKeys(next.getKeyspec(), next.getKeyalg());               
            userData.setCertificateProfileId(certificateProfileId);
            userData.setCAId(cAInfo.getCAId());
            userData.setPassword(password);
            userData.setStatus(UserDataConstants.STATUS_NEW);
            userAdminSession.changeUser(admin, userData, true);
            X509Certificate cert;
            if(eDate == null){
                cert =  (X509Certificate) signSession.createCertificate(admin,userData.getUsername(),password, keys.getPublic());
            }else{
              cert =  (X509Certificate) signSession.createCertificate(admin,userData.getUsername(),password, keys.getPublic(), -1, bDate, eDate);
            }
           
            genCertificates.add(cert);     
            // Generate Keystore
            // Fetch CA Cert Chain.         
            Collection<java.security.cert.Certificate> chain =  caAdminSession.getCAInfo(admin, cAInfo.getCAId()).getCertificateChain();
            String alias = CertTools.getPartFromDN(CertTools.getSubjectDN(cert), "CN");
            if (alias == null){
              alias = userData.getUsername();
            }               
            java.security.KeyStore pkcs12 = KeyTools.createP12(alias, keys.getPrivate(), cert, chain);

            retval.add(new TokenCertificateResponseWS(new KeyStore(pkcs12, userDataWS.getPassword())));
          }else{
View Full Code Here

TOP

Related Classes of org.ejbca.core.model.ra.UserDataVO

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.