Search in sources :

Example 6 with PermissionDeniedException

use of com.cloud.exception.PermissionDeniedException in project cloudstack by apache.

the class ProjectManagerImpl method createProject.

@Override
@ActionEvent(eventType = EventTypes.EVENT_PROJECT_CREATE, eventDescription = "creating project", create = true)
@DB
public Project createProject(final String name, final String displayText, String accountName, final Long domainId) throws ResourceAllocationException {
    Account caller = CallContext.current().getCallingAccount();
    Account owner = caller;
    //check if the user authorized to create the project
    if (_accountMgr.isNormalUser(caller.getId()) && !_allowUserToCreateProject) {
        throw new PermissionDeniedException("Regular user is not permitted to create a project");
    }
    //Verify request parameters
    if ((accountName != null && domainId == null) || (domainId != null && accountName == null)) {
        throw new InvalidParameterValueException("Account name and domain id must be specified together");
    }
    if (accountName != null) {
        owner = _accountMgr.finalizeOwner(caller, accountName, domainId, null);
    }
    //don't allow 2 projects with the same name inside the same domain
    if (_projectDao.findByNameAndDomain(name, owner.getDomainId()) != null) {
        throw new InvalidParameterValueException("Project with name " + name + " already exists in domain id=" + owner.getDomainId());
    }
    //do resource limit check
    _resourceLimitMgr.checkResourceLimit(owner, ResourceType.project);
    final Account ownerFinal = owner;
    return Transaction.execute(new TransactionCallback<Project>() {

        @Override
        public Project doInTransaction(TransactionStatus status) {
            //Create an account associated with the project
            StringBuilder acctNm = new StringBuilder("PrjAcct-");
            acctNm.append(name).append("-").append(ownerFinal.getDomainId());
            Account projectAccount = _accountMgr.createAccount(acctNm.toString(), Account.ACCOUNT_TYPE_PROJECT, null, domainId, null, null, UUID.randomUUID().toString());
            Project project = _projectDao.persist(new ProjectVO(name, displayText, ownerFinal.getDomainId(), projectAccount.getId()));
            //assign owner to the project
            assignAccountToProject(project, ownerFinal.getId(), ProjectAccount.Role.Admin);
            if (project != null) {
                CallContext.current().setEventDetails("Project id=" + project.getId());
                CallContext.current().putContextParameter(Project.class, project.getUuid());
            }
            //Increment resource count
            _resourceLimitMgr.incrementResourceCount(ownerFinal.getId(), ResourceType.project);
            return project;
        }
    });
}
Also used : Account(com.cloud.user.Account) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) TransactionStatus(com.cloud.utils.db.TransactionStatus) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Example 7 with PermissionDeniedException

use of com.cloud.exception.PermissionDeniedException in project cloudstack by apache.

the class CreateTemplateCmd method getEntityOwnerId.

@Override
public long getEntityOwnerId() {
    Long volumeId = getVolumeId();
    Long snapshotId = getSnapshotId();
    Account callingAccount = CallContext.current().getCallingAccount();
    if (volumeId != null) {
        Volume volume = _entityMgr.findById(Volume.class, volumeId);
        if (volume != null) {
            _accountService.checkAccess(callingAccount, SecurityChecker.AccessType.UseEntry, false, volume);
        } else {
            throw new InvalidParameterValueException("Unable to find volume by id=" + volumeId);
        }
    } else {
        Snapshot snapshot = _entityMgr.findById(Snapshot.class, snapshotId);
        if (snapshot != null) {
            _accountService.checkAccess(callingAccount, SecurityChecker.AccessType.UseEntry, false, snapshot);
        } else {
            throw new InvalidParameterValueException("Unable to find snapshot by id=" + snapshotId);
        }
    }
    if (projectId != null) {
        final Project project = _projectService.getProject(projectId);
        if (project != null) {
            if (project.getState() == Project.State.Active) {
                Account projectAccount = _accountService.getAccount(project.getProjectAccountId());
                _accountService.checkAccess(callingAccount, SecurityChecker.AccessType.UseEntry, false, projectAccount);
                return project.getProjectAccountId();
            } else {
                final PermissionDeniedException ex = new PermissionDeniedException("Can't add resources to the project with specified projectId in state=" + project.getState() + " as it's no longer active");
                ex.addProxyObject(project.getUuid(), "projectId");
                throw ex;
            }
        } else {
            throw new InvalidParameterValueException("Unable to find project by id");
        }
    }
    return callingAccount.getId();
}
Also used : Account(com.cloud.user.Account) Snapshot(com.cloud.storage.Snapshot) Project(com.cloud.projects.Project) Volume(com.cloud.storage.Volume) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException)

Example 8 with PermissionDeniedException

use of com.cloud.exception.PermissionDeniedException in project cloudstack by apache.

the class ApiServer method verifyRequest.

@Override
public boolean verifyRequest(final Map<String, Object[]> requestParameters, final Long userId) throws ServerApiException {
    try {
        String apiKey = null;
        String secretKey = null;
        String signature = null;
        String unsignedRequest = null;
        final String[] command = (String[]) requestParameters.get(ApiConstants.COMMAND);
        if (command == null) {
            s_logger.info("missing command, ignoring request...");
            return false;
        }
        final String commandName = command[0];
        // if userId not null, that mean that user is logged in
        if (userId != null) {
            final User user = ApiDBUtils.findUserById(userId);
            try {
                checkCommandAvailable(user, commandName);
            } catch (final RequestLimitException ex) {
                s_logger.debug(ex.getMessage());
                throw new ServerApiException(ApiErrorCode.API_LIMIT_EXCEED, ex.getMessage());
            } catch (final PermissionDeniedException ex) {
                s_logger.debug("The user with id:" + userId + " is not allowed to request the API command or the API command does not exist: " + commandName);
                throw new ServerApiException(ApiErrorCode.UNSUPPORTED_ACTION_ERROR, "The user is not allowed to request the API command or the API command does not exist");
            }
            return true;
        } else {
            // check against every available command to see if the command exists or not
            if (!s_apiNameCmdClassMap.containsKey(commandName) && !commandName.equals("login") && !commandName.equals("logout")) {
                s_logger.debug("The user with id:" + userId + " is not allowed to request the API command or the API command does not exist: " + commandName);
                throw new ServerApiException(ApiErrorCode.UNSUPPORTED_ACTION_ERROR, "The user is not allowed to request the API command or the API command does not exist");
            }
        }
        // - build a request string with sorted params, make sure it's all lowercase
        // - sign the request, verify the signature is the same
        final List<String> parameterNames = new ArrayList<String>();
        for (final Object paramNameObj : requestParameters.keySet()) {
            // put the name in a list that we'll sort later
            parameterNames.add((String) paramNameObj);
        }
        Collections.sort(parameterNames);
        String signatureVersion = null;
        String expires = null;
        for (final String paramName : parameterNames) {
            // parameters come as name/value pairs in the form String/String[]
            final String paramValue = ((String[]) requestParameters.get(paramName))[0];
            if (ApiConstants.SIGNATURE.equalsIgnoreCase(paramName)) {
                signature = paramValue;
            } else {
                if (ApiConstants.API_KEY.equalsIgnoreCase(paramName)) {
                    apiKey = paramValue;
                } else if (ApiConstants.SIGNATURE_VERSION.equalsIgnoreCase(paramName)) {
                    signatureVersion = paramValue;
                } else if (ApiConstants.EXPIRES.equalsIgnoreCase(paramName)) {
                    expires = paramValue;
                }
                if (unsignedRequest == null) {
                    unsignedRequest = paramName + "=" + URLEncoder.encode(paramValue, HttpUtils.UTF_8).replaceAll("\\+", "%20");
                } else {
                    unsignedRequest = unsignedRequest + "&" + paramName + "=" + URLEncoder.encode(paramValue, HttpUtils.UTF_8).replaceAll("\\+", "%20");
                }
            }
        }
        // if api/secret key are passed to the parameters
        if ((signature == null) || (apiKey == null)) {
            s_logger.debug("Expired session, missing signature, or missing apiKey -- ignoring request. Signature: " + signature + ", apiKey: " + apiKey);
            // no signature, bad request
            return false;
        }
        Date expiresTS = null;
        // FIXME: Hard coded signature, why not have an enum
        if ("3".equals(signatureVersion)) {
            // New signature authentication. Check for expire parameter and its validity
            if (expires == null) {
                s_logger.debug("Missing Expires parameter -- ignoring request. Signature: " + signature + ", apiKey: " + apiKey);
                return false;
            }
            synchronized (DateFormatToUse) {
                try {
                    expiresTS = DateFormatToUse.parse(expires);
                } catch (final ParseException pe) {
                    s_logger.debug("Incorrect date format for Expires parameter", pe);
                    return false;
                }
            }
            final Date now = new Date(System.currentTimeMillis());
            if (expiresTS.before(now)) {
                s_logger.debug("Request expired -- ignoring ...sig: " + signature + ", apiKey: " + apiKey);
                return false;
            }
        }
        final TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.CLOUD_DB);
        txn.close();
        User user = null;
        // verify there is a user with this api key
        final Pair<User, Account> userAcctPair = accountMgr.findUserByApiKey(apiKey);
        if (userAcctPair == null) {
            s_logger.debug("apiKey does not map to a valid user -- ignoring request, apiKey: " + apiKey);
            return false;
        }
        user = userAcctPair.first();
        final Account account = userAcctPair.second();
        if (user.getState() != Account.State.enabled || !account.getState().equals(Account.State.enabled)) {
            s_logger.info("disabled or locked user accessing the api, userid = " + user.getId() + "; name = " + user.getUsername() + "; state: " + user.getState() + "; accountState: " + account.getState());
            return false;
        }
        try {
            checkCommandAvailable(user, commandName);
        } catch (final RequestLimitException ex) {
            s_logger.debug(ex.getMessage());
            throw new ServerApiException(ApiErrorCode.API_LIMIT_EXCEED, ex.getMessage());
        } catch (final PermissionDeniedException ex) {
            s_logger.debug("The given command:" + commandName + " does not exist or it is not available for user");
            throw new ServerApiException(ApiErrorCode.UNSUPPORTED_ACTION_ERROR, "The given command:" + commandName + " does not exist or it is not available for user with id:" + userId);
        }
        // verify secret key exists
        secretKey = user.getSecretKey();
        if (secretKey == null) {
            s_logger.info("User does not have a secret key associated with the account -- ignoring request, username: " + user.getUsername());
            return false;
        }
        unsignedRequest = unsignedRequest.toLowerCase();
        final Mac mac = Mac.getInstance("HmacSHA1");
        final SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(), "HmacSHA1");
        mac.init(keySpec);
        mac.update(unsignedRequest.getBytes());
        final byte[] encryptedBytes = mac.doFinal();
        final String computedSignature = Base64.encodeBase64String(encryptedBytes);
        final boolean equalSig = ConstantTimeComparator.compareStrings(signature, computedSignature);
        if (!equalSig) {
            s_logger.info("User signature: " + signature + " is not equaled to computed signature: " + computedSignature);
        } else {
            CallContext.register(user, account);
        }
        return equalSig;
    } catch (final ServerApiException ex) {
        throw ex;
    } catch (final Exception ex) {
        s_logger.error("unable to verify request signature");
    }
    return false;
}
Also used : UserAccount(com.cloud.user.UserAccount) Account(com.cloud.user.Account) User(com.cloud.user.User) RequestLimitException(com.cloud.exception.RequestLimitException) ArrayList(java.util.ArrayList) Date(java.util.Date) ResponseDate(org.apache.http.protocol.ResponseDate) Mac(javax.crypto.Mac) AccountLimitException(com.cloud.exception.AccountLimitException) HttpException(org.apache.http.HttpException) InsufficientCapacityException(com.cloud.exception.InsufficientCapacityException) ServerApiException(org.apache.cloudstack.api.ServerApiException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) InterruptedIOException(java.io.InterruptedIOException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) CloudAuthenticationException(com.cloud.exception.CloudAuthenticationException) IOException(java.io.IOException) RequestLimitException(com.cloud.exception.RequestLimitException) URISyntaxException(java.net.URISyntaxException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) ParseException(java.text.ParseException) EventBusException(org.apache.cloudstack.framework.events.EventBusException) ConfigurationException(javax.naming.ConfigurationException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) NoSuchBeanDefinitionException(org.springframework.beans.factory.NoSuchBeanDefinitionException) ConnectionClosedException(org.apache.http.ConnectionClosedException) TransactionLegacy(com.cloud.utils.db.TransactionLegacy) ServerApiException(org.apache.cloudstack.api.ServerApiException) SecretKeySpec(javax.crypto.spec.SecretKeySpec) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) ExceptionProxyObject(com.cloud.utils.exception.ExceptionProxyObject) ResponseObject(org.apache.cloudstack.api.ResponseObject) ParseException(java.text.ParseException)

Example 9 with PermissionDeniedException

use of com.cloud.exception.PermissionDeniedException in project cloudstack by apache.

the class ApiResponseHelper method queryJobResult.

@Override
public AsyncJobResponse queryJobResult(QueryAsyncJobResultCmd cmd) {
    Account caller = CallContext.current().getCallingAccount();
    AsyncJob job = _entityMgr.findById(AsyncJob.class, cmd.getId());
    if (job == null) {
        throw new InvalidParameterValueException("Unable to find a job by id " + cmd.getId());
    }
    User userJobOwner = _accountMgr.getUserIncludingRemoved(job.getUserId());
    Account jobOwner = _accountMgr.getAccount(userJobOwner.getAccountId());
    //check permissions
    if (_accountMgr.isNormalUser(caller.getId())) {
        //regular user can see only jobs he owns
        if (caller.getId() != jobOwner.getId()) {
            throw new PermissionDeniedException("Account " + caller + " is not authorized to see job id=" + job.getId());
        }
    } else if (_accountMgr.isDomainAdmin(caller.getId())) {
        _accountMgr.checkAccess(caller, null, true, jobOwner);
    }
    return createAsyncJobResponse(_jobMgr.queryJob(cmd.getId(), true));
}
Also used : ProjectAccount(com.cloud.projects.ProjectAccount) UserAccount(com.cloud.user.UserAccount) Account(com.cloud.user.Account) User(com.cloud.user.User) VpnUser(com.cloud.network.VpnUser) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) AsyncJob(org.apache.cloudstack.framework.jobs.AsyncJob)

Example 10 with PermissionDeniedException

use of com.cloud.exception.PermissionDeniedException in project cloudstack by apache.

the class NetworkServiceImpl method createPhysicalNetwork.

@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_PHYSICAL_NETWORK_CREATE, eventDescription = "Creating Physical Network", create = true)
public PhysicalNetwork createPhysicalNetwork(final Long zoneId, final String vnetRange, final String networkSpeed, final List<String> isolationMethods, String broadcastDomainRangeStr, final Long domainId, final List<String> tags, final String name) {
    // Check if zone exists
    if (zoneId == null) {
        throw new InvalidParameterValueException("Please specify a valid zone.");
    }
    DataCenterVO zone = _dcDao.findById(zoneId);
    if (zone == null) {
        throw new InvalidParameterValueException("Please specify a valid zone.");
    }
    if (Grouping.AllocationState.Enabled == zone.getAllocationState()) {
        // TBD: Send uuid instead of zoneId; may have to hardcode tablename in call to addProxyObject().
        throw new PermissionDeniedException("Cannot create PhysicalNetwork since the Zone is currently enabled, zone Id: " + zoneId);
    }
    NetworkType zoneType = zone.getNetworkType();
    if (zoneType == NetworkType.Basic) {
        if (!_physicalNetworkDao.listByZone(zoneId).isEmpty()) {
            // TBD: Send uuid instead of zoneId; may have to hardcode tablename in call to addProxyObject().
            throw new CloudRuntimeException("Cannot add the physical network to basic zone id: " + zoneId + ", there is a physical network already existing in this basic Zone");
        }
    }
    if (tags != null && tags.size() > 1) {
        throw new InvalidParameterException("Only one tag can be specified for a physical network at this time");
    }
    if (isolationMethods != null && isolationMethods.size() > 1) {
        throw new InvalidParameterException("Only one isolationMethod can be specified for a physical network at this time");
    }
    if (vnetRange != null) {
        // Verify zone type
        if (zoneType == NetworkType.Basic || (zoneType == NetworkType.Advanced && zone.isSecurityGroupEnabled())) {
            throw new InvalidParameterValueException("Can't add vnet range to the physical network in the zone that supports " + zoneType + " network, Security Group enabled: " + zone.isSecurityGroupEnabled());
        }
    }
    BroadcastDomainRange broadcastDomainRange = null;
    if (broadcastDomainRangeStr != null && !broadcastDomainRangeStr.isEmpty()) {
        try {
            broadcastDomainRange = PhysicalNetwork.BroadcastDomainRange.valueOf(broadcastDomainRangeStr.toUpperCase());
        } catch (IllegalArgumentException ex) {
            throw new InvalidParameterValueException("Unable to resolve broadcastDomainRange '" + broadcastDomainRangeStr + "' to a supported value {Pod or Zone}");
        }
        // in Acton release you can specify only Zone broadcastdomain type in Advance zone, and Pod in Basic
        if (zoneType == NetworkType.Basic && broadcastDomainRange != null && broadcastDomainRange != BroadcastDomainRange.POD) {
            throw new InvalidParameterValueException("Basic zone can have broadcast domain type of value " + BroadcastDomainRange.POD + " only");
        } else if (zoneType == NetworkType.Advanced && broadcastDomainRange != null && broadcastDomainRange != BroadcastDomainRange.ZONE) {
            throw new InvalidParameterValueException("Advance zone can have broadcast domain type of value " + BroadcastDomainRange.ZONE + " only");
        }
    }
    if (broadcastDomainRange == null) {
        if (zoneType == NetworkType.Basic) {
            broadcastDomainRange = PhysicalNetwork.BroadcastDomainRange.POD;
        } else {
            broadcastDomainRange = PhysicalNetwork.BroadcastDomainRange.ZONE;
        }
    }
    try {
        final BroadcastDomainRange broadcastDomainRangeFinal = broadcastDomainRange;
        return Transaction.execute(new TransactionCallback<PhysicalNetworkVO>() {

            @Override
            public PhysicalNetworkVO doInTransaction(TransactionStatus status) {
                // Create the new physical network in the database
                long id = _physicalNetworkDao.getNextInSequence(Long.class, "id");
                PhysicalNetworkVO pNetwork = new PhysicalNetworkVO(id, zoneId, vnetRange, networkSpeed, domainId, broadcastDomainRangeFinal, name);
                pNetwork.setTags(tags);
                pNetwork.setIsolationMethods(isolationMethods);
                pNetwork = _physicalNetworkDao.persist(pNetwork);
                // Add vnet entries for the new zone if zone type is Advanced
                if (vnetRange != null) {
                    addOrRemoveVnets(vnetRange.split(","), pNetwork);
                }
                // add VirtualRouter as the default network service provider
                addDefaultVirtualRouterToPhysicalNetwork(pNetwork.getId());
                if (pNetwork.getIsolationMethods().contains("GRE"))
                    addDefaultOvsToPhysicalNetwork(pNetwork.getId());
                // add security group provider to the physical network
                addDefaultSecurityGroupProviderToPhysicalNetwork(pNetwork.getId());
                // add VPCVirtualRouter as the defualt network service provider
                addDefaultVpcVirtualRouterToPhysicalNetwork(pNetwork.getId());
                // add baremetal as the defualt network service provider
                addDefaultBaremetalProvidersToPhysicalNetwork(pNetwork.getId());
                //Add Internal Load Balancer element as a default network service provider
                addDefaultInternalLbProviderToPhysicalNetwork(pNetwork.getId());
                return pNetwork;
            }
        });
    } catch (Exception ex) {
        s_logger.warn("Exception: ", ex);
        throw new CloudRuntimeException("Fail to create a physical network");
    }
}
Also used : DataCenterVO(com.cloud.dc.DataCenterVO) BroadcastDomainRange(com.cloud.network.PhysicalNetwork.BroadcastDomainRange) TransactionStatus(com.cloud.utils.db.TransactionStatus) InvalidParameterException(java.security.InvalidParameterException) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) InsufficientCapacityException(com.cloud.exception.InsufficientCapacityException) InsufficientAddressCapacityException(com.cloud.exception.InsufficientAddressCapacityException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) SQLException(java.sql.SQLException) UnknownHostException(java.net.UnknownHostException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) UnsupportedServiceException(com.cloud.exception.UnsupportedServiceException) ConfigurationException(javax.naming.ConfigurationException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) InvalidParameterException(java.security.InvalidParameterException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) NetworkType(com.cloud.dc.DataCenter.NetworkType) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) PhysicalNetworkVO(com.cloud.network.dao.PhysicalNetworkVO) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Aggregations

PermissionDeniedException (com.cloud.exception.PermissionDeniedException)82 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)70 Account (com.cloud.user.Account)69 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)26 ActionEvent (com.cloud.event.ActionEvent)23 ArrayList (java.util.ArrayList)22 Project (com.cloud.projects.Project)16 DB (com.cloud.utils.db.DB)15 HashMap (java.util.HashMap)15 DataCenterVO (com.cloud.dc.DataCenterVO)13 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)13 ConfigurationException (javax.naming.ConfigurationException)13 DomainVO (com.cloud.domain.DomainVO)11 Pair (com.cloud.utils.Pair)11 List (java.util.List)11 AgentUnavailableException (com.cloud.exception.AgentUnavailableException)10 InsufficientCapacityException (com.cloud.exception.InsufficientCapacityException)10 VolumeVO (com.cloud.storage.VolumeVO)10 TransactionStatus (com.cloud.utils.db.TransactionStatus)10 OperationTimedoutException (com.cloud.exception.OperationTimedoutException)8