Package org.ejbca.util

Examples of org.ejbca.util.IPatternLogger


    boolean isRejectedStep1 = false;

    // Get Significant user Id
    final CAInfo significantcAInfo;
    final ArrayList<java.security.cert.Certificate> genCertificates = new ArrayList<java.security.cert.Certificate>();
    final IPatternLogger logger = TransactionLogger.getPatternLogger();
        logAdminName(admin,logger);
    try {
      significantcAInfo = caAdminSession.getCAInfoOrThrowException(intAdmin, userDataWS.getCaName());
    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{
            throw EjbcaWSHelper.getEjbcaException("Error in request, only REQUESTTYPE_PKCS10_REQUEST and REQUESTTYPE_KEYSTORE_REQUEST are supported token requests.",
              logger, ErrorCode.NOT_SUPPORTED_REQUEST_TYPE, null);
          }
      }

    } catch(Exception e){
            throw EjbcaWSHelper.getInternalException(e, logger);
    } finally{
      userAdminSession.setUserStatus(admin, userDataWS.getUsername(), UserDataConstants.STATUS_GENERATED);
    }

    // Add hard token data
    HardToken hardToken;
    String signatureInitialPIN = "";
    String signaturePUK = "";
    String basicInitialPIN = "";
    String basicPUK = "";
    Iterator<PinDataWS> iter = hardTokenDataWS.getPinDatas().iterator();
    while(iter.hasNext()){
      PinDataWS pinData = iter.next();
      switch(pinData.getType()){
      case HardTokenConstants.PINTYPE_BASIC :
        basicInitialPIN = pinData.getInitialPIN();
        basicPUK = pinData.getPUK();
        break;
      case HardTokenConstants.PINTYPE_SIGNATURE :
        signatureInitialPIN = pinData.getInitialPIN();
        signaturePUK = pinData.getPUK();
        break;
      default :
        throw EjbcaWSHelper.getEjbcaException("Unsupported PIN Type " + pinData.getType(),
          logger, ErrorCode.NOT_SUPPORTED_PIN_TYPE, null);
      }
    }
    int tokenType = SwedishEIDHardToken.THIS_TOKENTYPE;
    switch (hardTokenDataWS.getTokenType()){
    case HardTokenConstants.TOKENTYPE_SWEDISHEID :
      hardToken = new SwedishEIDHardToken(basicInitialPIN,basicPUK,signatureInitialPIN,signaturePUK,0)
      break;
    case HardTokenConstants.TOKENTYPE_ENHANCEDEID :
      hardToken = new EnhancedEIDHardToken(signatureInitialPIN,signaturePUK,basicInitialPIN,basicPUK,false,0);
      tokenType = EnhancedEIDHardToken.THIS_TOKENTYPE;
      break;
    default:
      throw EjbcaWSHelper.getEjbcaException("Unsupported Token Type : " + hardTokenDataWS.getTokenType(),
        logger, ErrorCode.NOT_SUPPORTED_TOKEN_TYPE, null);

    }

    hardToken.setLabel(hardTokenDataWS.getLabel());
      if(overwriteExistingSN){
        if(hardTokenExists){
          try {
            hardTokenSession.removeHardToken(admin, hardTokenDataWS.getHardTokenSN());
          } catch (HardTokenDoesntExistsException e) {
            throw EjbcaWSHelper.getEjbcaException(e, logger, ErrorCode.HARD_TOKEN_NOT_EXISTS, Level.ERROR);
          }
        }
      }
      hardTokenSession.addHardToken(admin, hardTokenDataWS.getHardTokenSN(), userDataWS.getUsername(), significantcAInfo.getSubjectDN(), tokenType, hardToken, genCertificates, hardTokenDataWS.getCopyOfSN());

      if(ar!= null){
        approvalSession.markAsStepDone(admin, ar.generateApprovalId(), GenerateTokenApprovalRequest.STEP_1_GENERATETOKEN);
      }
        } catch( EjbcaException e) {
            throw e;
        } catch (FinderException e) {
            throw EjbcaWSHelper.getInternalException(e, logger);
        } catch (RuntimeException e) {  // EJBException, ClassCastException, ...
            throw EjbcaWSHelper.getInternalException(e, logger);
        } finally {
            logger.writeln();
            logger.flush();
        }
    return retval;  
  }
View Full Code Here


   * @see org.ejbca.core.protocol.ws.common.IEjbcaWS#existsHardToken(java.lang.String)
   */
  public boolean existsHardToken(String hardTokenSN) throws EjbcaException{
    final EjbcaWSHelper ejbhelper = new EjbcaWSHelper(wsContext, authorizationSession, caAdminSession, certificateProfileSession, certificateStoreSession, endEntityProfileSession, hardTokenSession, userAdminSession);

        final IPatternLogger logger = TransactionLogger.getPatternLogger();
        try {
            final Admin admin = ejbhelper.getAdmin();
            logAdminName(admin,logger);
      return hardTokenSession.existsHardToken(admin, hardTokenSN);
    } catch (AuthorizationDeniedException e) {
            throw EjbcaWSHelper.getEjbcaException(e, logger, ErrorCode.NOT_AUTHORIZED, Level.ERROR);
        } catch (RuntimeException e) {  // EJBException, ClassCastException, ...
            throw EjbcaWSHelper.getInternalException(e, logger);
        } finally {
            logger.writeln();
            logger.flush();
        }
  }
View Full Code Here

    ApprovalRequest ar = null;
    boolean isApprovedStep0 = false;
    boolean isRejectedStep0 = false;

    HardTokenData hardTokenData = null;
    final IPatternLogger logger = TransactionLogger.getPatternLogger();
        logAdminName(admin,logger);
        try {
    try{
      hardTokenData = hardTokenSession.getHardToken(admin, hardTokenSN, viewPUKData);
      if(hardTokenData == null){
        throw new HardTokenDoesntExistsException("Error, hard token with SN " + hardTokenSN + " doesn't exist.");
      }
      ejbhelper.isAuthorizedToHardTokenData(admin, hardTokenData.getUsername(), viewPUKData);
    }catch(AuthorizationDeniedException e){
      boolean genNewRequest = false;
      if(WebServiceConfiguration.getApprovalForHardTokenData()){
        // Check Approvals
        // Exists an GenTokenCertificates
          Admin intAdmin = Admin.getInternalAdmin();
          UserDataVO userData = userAdminSession.findUser(intAdmin, hardTokenData.getUsername());
          if (userData == null) {
            String msg = intres.getLocalizedMessage("ra.errorentitynotexist", hardTokenData.getUsername());             
            throw new NotFoundException(msg);
          }
          int caid = userData.getCAId();
          caAdminSession.verifyExistenceOfCA(caid);
          ar = new GenerateTokenApprovalRequest(userData.getUsername(), userData.getDN(), hardTokenData.getHardToken().getLabel(),admin,null,WebServiceConfiguration.getNumberOfRequiredApprovals(),caid,userData.getEndEntityProfileId());
          int status = ApprovalDataVO.STATUS_REJECTED;          
          try{
            if(!WebServiceConfiguration.getApprovalForGenTokenCertificates()){
              throw new ApprovalException("");
            }
            status = approvalSession.isApproved(admin, ar.generateApprovalId(), 0);
            isApprovedStep0 =  status == ApprovalDataVO.STATUS_APPROVED;
           
            if(   status == ApprovalDataVO.STATUS_EXPIREDANDNOTIFIED
                || status == ApprovalDataVO.STATUS_EXPIRED
                || status == ApprovalDataVO.STATUS_REJECTED){
              throw new ApprovalException("");
            }
          }catch(ApprovalException e2){
            // GenTokenCertificates approval doesn't exists, try a getHardTokenData request
            if(!WebServiceConfiguration.getApprovalForHardTokenData()){
                throw new AuthorizationDeniedException("JaxWS isn't configured for getHardTokenData approvals.");
            }
            ar = new ViewHardTokenDataApprovalRequest(userData.getUsername(), userData.getDN(), hardTokenSN, true,admin,null,WebServiceConfiguration.getNumberOfRequiredApprovals(),userData.getCAId(),userData.getEndEntityProfileId());
            try{
              status = approvalSession.isApproved(admin, ar.generateApprovalId());
              isApprovedStep0 = status == ApprovalDataVO.STATUS_APPROVED;
              isRejectedStep0 =  status == ApprovalDataVO.STATUS_REJECTED;
              if(   status == ApprovalDataVO.STATUS_EXPIREDANDNOTIFIED
                     || status == ApprovalDataVO.STATUS_EXPIRED){
                throw new ApprovalException("");
              }
            }catch(ApprovalException e3){
              genNewRequest = true;
            }catch(ApprovalRequestExpiredException e3){
              genNewRequest = true;
            }
            if(genNewRequest){
                            //  Add approval Request
              try{
                approvalSession.addApprovalRequest(admin, ar, globalConfigurationSession.getCachedGlobalConfiguration(admin));
                throw new WaitingForApprovalException("Adding approval to view hard token data with id " + ar.generateApprovalId(), ar.generateApprovalId());
              }catch(ApprovalException e4){
                throw EjbcaWSHelper.getEjbcaException(e4, logger, ErrorCode.APPROVAL_ALREADY_EXISTS, null);
              }
            }
          }   
      }else{
        throw e;
      }
    }
   
    if(ar != null && isRejectedStep0){
      throw new ApprovalRequestExecutionException("The approval for id " + ar.generateApprovalId() + " have been rejected.");
    }
   
    if(ar != null && ! isApprovedStep0){
      throw new WaitingForApprovalException("The approval for id " + ar.generateApprovalId() + " have not yet been approved", ar.generateApprovalId());
    }
   
      Collection<java.security.cert.Certificate> certs = hardTokenSession.findCertificatesInHardToken(admin, hardTokenSN);

      if(onlyValidCertificates){
        certs = ejbhelper.returnOnlyValidCertificates(admin, certs);
      }

      retval = ejbhelper.convertHardTokenToWS(hardTokenData,certs,viewPUKData);   

      if(ar != null){
        try {
          approvalSession.markAsStepDone(admin, ar.generateApprovalId(), 0);
        } catch (ApprovalException e) {
          throw EjbcaWSHelper.getEjbcaException(e, logger, ErrorCode.APPROVAL_REQUEST_ID_NOT_EXIST, null);
        }
      }
        } catch (RuntimeException e) {  // EJBException, ...
            throw EjbcaWSHelper.getInternalException(e, logger);
    } finally {
          logger.writeln();
          logger.flush();
    }
    return retval;
  }
View Full Code Here

   * @see org.ejbca.core.protocol.ws.common.IEjbcaWS#getHardTokenDatas(java.lang.String)
   */
  public List<HardTokenDataWS> getHardTokenDatas(String username, boolean viewPUKData, boolean onlyValidCertificates)
    throws CADoesntExistsException, AuthorizationDeniedException, EjbcaException {
    EjbcaWSHelper ejbhelper = new EjbcaWSHelper(wsContext, authorizationSession, caAdminSession, certificateProfileSession, certificateStoreSession, endEntityProfileSession, hardTokenSession, userAdminSession);
        final IPatternLogger logger = TransactionLogger.getPatternLogger();
        final Admin admin = ejbhelper.getAdmin();
        logAdminName(admin,logger);
        try {
            return getHardTokenDatas(admin,username, viewPUKData, onlyValidCertificates, logger);
        } catch( CADoesntExistsException t ) {
            logger.paramPut(TransactionTags.ERROR_MESSAGE.toString(), t.toString());
            throw t;
        } catch( AuthorizationDeniedException t ) {
            logger.paramPut(TransactionTags.ERROR_MESSAGE.toString(), t.toString());
            throw t;
        } catch( NotFoundException t ) {
            logger.paramPut(TransactionTags.ERROR_MESSAGE.toString(), t.toString());
            throw t;
        } catch (RuntimeException e) {  // EJBException, ...
            throw EjbcaWSHelper.getInternalException(e, logger);
        } finally {
            logger.writeln();
            logger.flush();
        }
  }
View Full Code Here

   */
  public void republishCertificate(String serialNumberInHex,String issuerDN) throws CADoesntExistsException, AuthorizationDeniedException, PublisherException, EjbcaException{
    EjbcaWSHelper ejbhelper = new EjbcaWSHelper(wsContext, authorizationSession, caAdminSession, certificateProfileSession, certificateStoreSession, endEntityProfileSession, hardTokenSession, userAdminSession);
    Admin admin = ejbhelper.getAdmin();

        final IPatternLogger logger = TransactionLogger.getPatternLogger();
        logAdminName(admin,logger);
    try{
      String bcIssuerDN = CertTools.stringToBCDNString(issuerDN);
      caAdminSession.verifyExistenceOfCA(bcIssuerDN.hashCode());
      CertReqHistory certreqhist = certificateStoreSession.getCertReqHistory(admin,new BigInteger(serialNumberInHex,16), bcIssuerDN);
      if(certreqhist == null){
        throw new PublisherException("Error: the  certificate with  serialnumber : " + serialNumberInHex +" and issuerdn " + issuerDN + " couldn't be found in database.");
      }

      ejbhelper.isAuthorizedToRepublish(admin, certreqhist.getUsername(),bcIssuerDN.hashCode());

      if(certreqhist != null){
        CertificateProfile certprofile = certificateProfileSession.getCertificateProfile(admin,certreqhist.getUserDataVO().getCertificateProfileId());
        java.security.cert.Certificate cert = certificateStoreSession.findCertificateByFingerprint(admin, certreqhist.getFingerprint());
        if(certprofile != null){
          CertificateInfo certinfo = certificateStoreSession.getCertificateInfo(admin, certreqhist.getFingerprint());
          if(certprofile.getPublisherList().size() > 0){
            if(publisherSession.storeCertificate(admin, certprofile.getPublisherList(), cert, certreqhist.getUserDataVO().getUsername(), certreqhist.getUserDataVO().getPassword(), certreqhist.getUserDataVO().getDN(),
                certinfo.getCAFingerprint(), certinfo.getStatus() , certinfo.getType(), certinfo.getRevocationDate().getTime(), certinfo.getRevocationReason(), certinfo.getTag(), certinfo.getCertificateProfileId(), certinfo.getUpdateTime().getTime(), certreqhist.getUserDataVO().getExtendedinformation())){
            }else{
              throw new PublisherException("Error: publication failed to at least one of the defined publishers.");
            }
          }else{
            throw new PublisherException("Error no publisher defined for the given certificate.");
          }

        }else{
          throw new PublisherException("Error : Certificate profile couldn't be found for the given certificate.");
        }   
      }
        } catch (RuntimeException e) {  // EJBException, ClassCastException, ...
            throw EjbcaWSHelper.getInternalException(e, logger);
        } finally {
            logger.writeln();
            logger.flush();
        }
  }
View Full Code Here

  public void customLog(int level, String type, String cAName, String username, Certificate certificate, String msg)
    throws CADoesntExistsException, AuthorizationDeniedException, EjbcaException {
    EjbcaWSHelper ejbhelper = new EjbcaWSHelper(wsContext, authorizationSession, caAdminSession, certificateProfileSession, certificateStoreSession, endEntityProfileSession, hardTokenSession, userAdminSession);
    Admin admin = ejbhelper.getAdmin();

        final IPatternLogger logger = TransactionLogger.getPatternLogger();
        logAdminName(admin,logger);
    try{
          // Check authorization to perform custom logging
      if(!authorizationSession.isAuthorized(admin, AccessRulesConstants.REGULAR_LOG_CUSTOM_EVENTS)) {
          Authorizer.throwAuthorizationException(admin, AccessRulesConstants.REGULAR_LOG_CUSTOM_EVENTS, null);
      }

      int event = LogConstants.EVENT_ERROR_CUSTOMLOG;
      switch (level) {
      case IEjbcaWS.CUSTOMLOG_LEVEL_ERROR:
        break;
      case IEjbcaWS.CUSTOMLOG_LEVEL_INFO:
        event = LogConstants.EVENT_INFO_CUSTOMLOG;
        break;
      default:
        throw EjbcaWSHelper.getEjbcaException("Illegal level "+ level + " sent to customLog call.", logger, ErrorCode.INVALID_LOG_LEVEL, null);
      }

      java.security.cert.Certificate logCert = null;
      if(certificate != null){
        logCert = CertificateHelper.getCertificate(certificate.getCertificateData());
      }

      int caId = admin.getCaId();
      if(cAName  != null){
        CAInfo cAInfo = caAdminSession.getCAInfoOrThrowException(admin, cAName);
        caId = cAInfo.getCAId();
      }

      String comment = type + " : " + msg;
      logSession.log(admin, caId, LogConstants.MODULE_CUSTOM, new Date(), username, (X509Certificate) logCert, event, comment);
    } catch (CertificateException e) {
            throw EjbcaWSHelper.getInternalException(e, logger);
        } catch (RuntimeException e) {  // EJBException, ClassCastException, ...
            throw EjbcaWSHelper.getInternalException(e, logger);
        } finally {
            logger.writeln();
            logger.flush();
        }
  }
View Full Code Here

   */
  public boolean deleteUserDataFromSource(List<String> userDataSourceNames, String searchString, boolean removeMultipleMatch) throws AuthorizationDeniedException, MultipleMatchException, UserDataSourceException, EjbcaException {
    boolean ret = false;
    EjbcaWSHelper ejbhelper = new EjbcaWSHelper(wsContext, authorizationSession, caAdminSession, certificateProfileSession, certificateStoreSession, endEntityProfileSession, hardTokenSession, userAdminSession);

        final IPatternLogger logger = TransactionLogger.getPatternLogger();
    try {

      Admin admin = ejbhelper.getAdmin();
            logAdminName(admin,logger);
      ArrayList<Integer> userDataSourceIds = new ArrayList<Integer>();
      Iterator<String> iter = userDataSourceNames.iterator();
      while(iter.hasNext()){
        String nextName = iter.next();
        int id = userDataSourceSession.getUserDataSourceId(admin, nextName);
        if(id == 0){
          throw new UserDataSourceException("Error: User Data Source with name : " + nextName + " couldn't be found, aborting operation.");
        }
        userDataSourceIds.add(Integer.valueOf(id));
      }
      ret = userDataSourceSession.removeUserData(admin, userDataSourceIds, searchString, removeMultipleMatch);
        } catch (RuntimeException e) {  // EJBException, ClassCastException, ...
            throw EjbcaWSHelper.getInternalException(e, logger);
        } finally {
            logger.writeln();
            logger.flush();
        }

    return ret;
  }
View Full Code Here

   * @see org.ejbca.core.protocol.ws.common.IEjbcaWS#isApproved(int)
   */
  public int isApproved(int approvalId) throws ApprovalException, EjbcaException, ApprovalRequestExpiredException{
    EjbcaWSHelper ejbhelper = new EjbcaWSHelper(wsContext, authorizationSession, caAdminSession, certificateProfileSession, certificateStoreSession, endEntityProfileSession, hardTokenSession, userAdminSession);

        final IPatternLogger logger = TransactionLogger.getPatternLogger();
        try {
            final Admin admin = ejbhelper.getAdmin(true);
            logAdminName(admin,logger);
      return approvalSession.isApproved(admin, approvalId);
    } catch (AuthorizationDeniedException e) {
            throw EjbcaWSHelper.getEjbcaException(e, logger, ErrorCode.NOT_AUTHORIZED, Level.ERROR);
        } catch (RuntimeException e) {  // EJBException, ClassCastException, ...
            throw EjbcaWSHelper.getInternalException(e, logger);
        } finally {
            logger.writeln();
            logger.flush();
        }
  }
View Full Code Here

    Certificate retval = null;
    EjbcaWSHelper ejbhelper = new EjbcaWSHelper(wsContext, authorizationSession, caAdminSession, certificateProfileSession, certificateStoreSession, endEntityProfileSession, hardTokenSession, userAdminSession);
    Admin admin = ejbhelper.getAdmin(true);
    String bcString = CertTools.stringToBCDNString(issuerDN);
    int caid = bcString.hashCode();
        final IPatternLogger logger = TransactionLogger.getPatternLogger();
        logAdminName(admin,logger);
    try {
      caAdminSession.verifyExistenceOfCA(caid);
      if(!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.REGULAR_VIEWCERTIFICATE)) {
          Authorizer.throwAuthorizationException(admin, AccessRulesConstants.REGULAR_VIEWCERTIFICATE, null);
      }
      if(!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.CAPREFIX + caid)) {
          Authorizer.throwAuthorizationException(admin, AccessRulesConstants.CAPREFIX + caid, null);
      }

      java.security.cert.Certificate cert = certificateStoreSession.findCertificateByIssuerAndSerno(admin, issuerDN, new BigInteger(certSNinHex,16));
      if(cert != null){
        retval = new Certificate(cert);
      }
    } catch (CertificateEncodingException e) {
            throw EjbcaWSHelper.getInternalException(e, logger);
        } catch (RuntimeException e) {  // EJBException, ...
            throw EjbcaWSHelper.getInternalException(e, logger);
        } finally {
            logger.writeln();
            logger.flush();
        }
    return retval;
  }
View Full Code Here

   */
  public NameAndId[] getAvailableCAs() throws EjbcaException, AuthorizationDeniedException {
    TreeMap<String,Integer> ret = new TreeMap<String,Integer>();
    EjbcaWSHelper ejbhelper = new EjbcaWSHelper(wsContext, authorizationSession, caAdminSession, certificateProfileSession, certificateStoreSession, endEntityProfileSession, hardTokenSession, userAdminSession);
    Admin admin = ejbhelper.getAdmin(true);
        final IPatternLogger logger = TransactionLogger.getPatternLogger();
        logAdminName(admin,logger);
    try {
      Collection<Integer> caids = caSession.getAvailableCAs(admin);
      HashMap<Integer, String> map = caAdminSession.getCAIdToNameMap(admin);
      for (Integer id : caids ) {
        String name = (String)map.get(id);
        if (name != null) {
          ret.put(name, id);
        }
      }
        } catch (RuntimeException e) {  // EJBException, ...
            throw EjbcaWSHelper.getInternalException(e, logger);
        } finally {
            logger.writeln();
            logger.flush();
        }
    return ejbhelper.convertTreeMapToArray(ret);
  }
View Full Code Here

TOP

Related Classes of org.ejbca.util.IPatternLogger

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.