Package org.ejbca.core.model.authorization

Examples of org.ejbca.core.model.authorization.AuthorizationDeniedException


      MessageContext msgContext = wsContext.getMessageContext();
      HttpServletRequest request = (HttpServletRequest) msgContext.get(MessageContext.SERVLET_REQUEST);
      X509Certificate[] certificates = (X509Certificate[]) request.getAttribute("javax.servlet.request.X509Certificate");

      if ((certificates == null) || (certificates[0] == null)) {
        throw new AuthorizationDeniedException("Error no client certificate recieved used for authentication.");
      }

      X509Certificate cert = certificates[0];
      admin = userAdminSession.getAdmin(cert);
      // Check that user have the administrator flag set.
      if(!allowNonAdmins){
        userAdminSession.checkIfCertificateBelongToUser(admin, CertTools.getSerialNumber(cert), CertTools.getIssuerDN(cert));
        if(!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.ROLE_ADMINISTRATOR)) {
            Authorizer.throwAuthorizationException(admin, AccessRulesConstants.ROLE_ADMINISTRATOR, null);
        }
      }

      try {
        certificateStoreSession.authenticate(cert, WebConfiguration.getRequireAdminCertificateInDatabase());
      } catch (AuthenticationFailedException e) {
        // The message from here is usually the same as we used to hardcode here...
              //String msg = intres.getLocalizedMessage("authentication.revokedormissing");
        // But it can also be that the certificate has expired, very unlikely since the SSL server checks that
        throw new AuthorizationDeniedException(e.getMessage());
      }
    } catch (EJBException e) {
      log.error("EJBCA WebService error: ",e);
      throw new EjbcaException(ErrorCode.INTERNAL_ERROR, e.getMessage());
    }
View Full Code Here


    CardVerifiableCertificate innercert = new CardVerifiableCertificate(innerreq);
    try {
      innercert.verify(pk);                   
      String msg = intres.getLocalizedMessage("cvc.error.renewsamekeys", holderref);             
      log.info(msg);
      throw new AuthorizationDeniedException(msg);
    } catch (SignatureException e) {
      // It was good if the verification failed
    } catch (NoSuchProviderException e) {
      String msg = intres.getLocalizedMessage("cvc.error.outersignature", holderref, e.getMessage());             
      log.warn(msg, e);
      throw new AuthorizationDeniedException(msg);
    } catch (InvalidKeyException e) {
      String msg = intres.getLocalizedMessage("cvc.error.outersignature", holderref, e.getMessage());             
      log.warn(msg, e);
      throw new AuthorizationDeniedException(msg);
    } catch (NoSuchAlgorithmException e) {
      String msg = intres.getLocalizedMessage("cvc.error.outersignature", holderref, e.getMessage());             
      log.info(msg, e);
      throw new AuthorizationDeniedException(msg);
    } catch (CertificateException e) {
      String msg = intres.getLocalizedMessage("cvc.error.outersignature", holderref, e.getMessage());             
      log.warn(msg, e);
      throw new AuthorizationDeniedException(msg);
    }
  }
View Full Code Here

      // 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 {
View Full Code Here

 
  private void revokeToken(Admin admin, String hardTokenSN, int reason, IPatternLogger logger) throws CADoesntExistsException, AuthorizationDeniedException,
      NotFoundException, EjbcaException, AlreadyRevokedException, ApprovalException, WaitingForApprovalException {
    ApprovalException lastApprovalException = null;
    WaitingForApprovalException lastWaitingForApprovalException = null;
    AuthorizationDeniedException lastAuthorizationDeniedException = null;
    AlreadyRevokedException lastAlreadyRevokedException = null;
    boolean success = false;
    try{
            logAdminName(admin,logger);
      Collection<java.security.cert.Certificate> certs = hardTokenSession.findCertificatesInHardToken(admin,hardTokenSN);
View Full Code Here

                }
                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.");
View Full Code Here

              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;
View Full Code Here

        // check authorization
        if (!authorizationSession.isAuthorizedNoLog(admin, "/super_administrator")) {
            String msg = intres.getLocalizedMessage("caadmin.notauthorizedtoremoveca", new Integer(caid));
            logSession.log(admin, caid, LogConstants.MODULE_CA, new java.util.Date(), null, null, LogConstants.EVENT_ERROR_NOTAUTHORIZEDTORESOURCE,
                    msg);
            throw new AuthorizationDeniedException(msg);
        }
        // Get CA from database
        try {
            CAData cadata = CAData.findByIdOrThrow(entityManager, Integer.valueOf(caid));
            // Remove CA
View Full Code Here

        int caid = cadata.getCaId().intValue();
        if (!authorizationSession.isAuthorizedNoLog(admin, "/super_administrator")) {
            String msg = intres.getLocalizedMessage("caadmin.notauthorizedtorenameca", Integer.valueOf(caid));
            logSession.log(admin, caid, LogConstants.MODULE_CA, new java.util.Date(), null, null, LogConstants.EVENT_ERROR_NOTAUTHORIZEDTORESOURCE,
                    msg);
            throw new AuthorizationDeniedException(msg);
        }
        CAData cadatanew = CAData.findByName(entityManager, newname);
        if (cadatanew != null) {
            cadatanew.getCaId();
            throw new CAExistsException(" CA name " + newname + " already exists.");
View Full Code Here

    public void addPublisher(String name, BasePublisher publisher) throws PublisherExistsException, AuthorizationDeniedException {
      if(authorizedToEditPublishers()){
        publishersession.addPublisher(administrator, name, publisher);
        this.info.publishersEdited();
      }else {
        throw new AuthorizationDeniedException("Not authorized to add publisher");
      }
    }   
View Full Code Here

    public void changePublisher(String name, BasePublisher publisher) throws AuthorizationDeniedException{
      if(authorizedToEditPublishers()){
        publishersession.changePublisher(administrator, name,publisher);  
    this.info.publishersEdited();
      }else {
        throw new AuthorizationDeniedException("Not authorized to edit publisher");
      }
    }
View Full Code Here

TOP

Related Classes of org.ejbca.core.model.authorization.AuthorizationDeniedException

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.