Search in sources :

Example 71 with PermissionDeniedException

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

the class AffinityGroupServiceImpl method updateVMAffinityGroups.

@Override
public UserVm updateVMAffinityGroups(Long vmId, List<Long> affinityGroupIds) {
    // Verify input parameters
    UserVmVO vmInstance = _userVmDao.findById(vmId);
    if (vmInstance == null) {
        throw new InvalidParameterValueException("Unable to find a virtual machine with id " + vmId);
    }
    // Check that the VM is stopped
    if (!vmInstance.getState().equals(State.Stopped)) {
        s_logger.warn("Unable to update affinity groups of the virtual machine " + vmInstance.toString() + " in state " + vmInstance.getState());
        throw new InvalidParameterValueException("Unable update affinity groups of the virtual machine " + vmInstance.toString() + " " + "in state " + vmInstance.getState() + "; make sure the virtual machine is stopped and not in an error state before updating.");
    }
    Account caller = CallContext.current().getCallingAccount();
    Account owner = _accountMgr.getAccount(vmInstance.getAccountId());
    // check that the affinity groups exist
    for (Long affinityGroupId : affinityGroupIds) {
        AffinityGroupVO ag = _affinityGroupDao.findById(affinityGroupId);
        if (ag == null) {
            throw new InvalidParameterValueException("Unable to find affinity group by id " + affinityGroupId);
        } else {
            // verify permissions
            _accountMgr.checkAccess(caller, null, true, owner, ag);
            // owner of these entities is same
            if (caller.getId() == Account.ACCOUNT_ID_SYSTEM || _accountMgr.isRootAdmin(caller.getId())) {
                if (ag.getAccountId() != owner.getAccountId()) {
                    throw new PermissionDeniedException("Affinity Group " + ag + " does not belong to the VM's account");
                }
            }
        }
    }
    _affinityGroupVMMapDao.updateMap(vmId, affinityGroupIds);
    if (s_logger.isDebugEnabled()) {
        s_logger.debug("Updated VM :" + vmId + " affinity groups to =" + affinityGroupIds);
    }
    // APIResponseHelper will pull out the updated affinitygroups.
    return vmInstance;
}
Also used : Account(com.cloud.user.Account) UserVmVO(com.cloud.vm.UserVmVO) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException)

Example 72 with PermissionDeniedException

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

the class DynamicRoleBasedAPIAccessChecker method checkAccess.

@Override
public boolean checkAccess(User user, String commandName) throws PermissionDeniedException {
    if (isDisabled()) {
        return true;
    }
    Account account = accountService.getAccount(user.getAccountId());
    if (account == null) {
        throw new PermissionDeniedException("The account id=" + user.getAccountId() + "for user id=" + user.getId() + "is null");
    }
    final Role accountRole = roleService.findRole(account.getRoleId());
    if (accountRole == null || accountRole.getId() < 1L) {
        denyApiAccess(commandName);
    }
    // Allow all APIs for root admins
    if (accountRole.getRoleType() == RoleType.Admin && accountRole.getId() == RoleType.Admin.getId()) {
        return true;
    }
    // Check against current list of permissions
    for (final RolePermission permission : roleService.findAllPermissionsBy(accountRole.getId())) {
        if (permission.getRule().matches(commandName)) {
            if (RolePermission.Permission.ALLOW.equals(permission.getPermission())) {
                return true;
            } else {
                denyApiAccess(commandName);
            }
        }
    }
    // Check annotations
    if (annotationRoleBasedApisMap.get(accountRole.getRoleType()) != null && annotationRoleBasedApisMap.get(accountRole.getRoleType()).contains(commandName)) {
        return true;
    }
    // Default deny all
    denyApiAccess(commandName);
    return false;
}
Also used : Account(com.cloud.user.Account) PermissionDeniedException(com.cloud.exception.PermissionDeniedException)

Example 73 with PermissionDeniedException

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

the class StaticRoleBasedAPIAccessChecker method checkAccess.

@Override
public boolean checkAccess(User user, String commandName) throws PermissionDeniedException {
    if (isDisabled()) {
        return true;
    }
    Account account = accountService.getAccount(user.getAccountId());
    if (account == null) {
        throw new PermissionDeniedException("The account id=" + user.getAccountId() + "for user id=" + user.getId() + "is null");
    }
    RoleType roleType = accountService.getRoleType(account);
    boolean isAllowed = commandsPropertiesOverrides.contains(commandName) ? commandsPropertiesRoleBasedApisMap.get(roleType).contains(commandName) : annotationRoleBasedApisMap.get(roleType).contains(commandName);
    if (isAllowed) {
        return true;
    }
    throw new PermissionDeniedException("The API does not exist or is blacklisted. Role type=" + roleType.toString() + " is not allowed to request the api: " + commandName);
}
Also used : Account(com.cloud.user.Account) PermissionDeniedException(com.cloud.exception.PermissionDeniedException)

Example 74 with PermissionDeniedException

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

the class SecurityGroupManagerImpl method authorizeSecurityGroupRule.

private List<SecurityGroupRuleVO> authorizeSecurityGroupRule(final Long securityGroupId, String protocol, Integer startPort, Integer endPort, Integer icmpType, Integer icmpCode, final List<String> cidrList, Map groupList, final SecurityRuleType ruleType) {
    Integer startPortOrType = null;
    Integer endPortOrCode = null;
    // Validate parameters
    SecurityGroup securityGroup = _securityGroupDao.findById(securityGroupId);
    if (securityGroup == null) {
        throw new InvalidParameterValueException("Unable to find security group by id " + securityGroupId);
    }
    if (cidrList == null && groupList == null) {
        throw new InvalidParameterValueException("At least one cidr or at least one security group needs to be specified");
    }
    Account caller = CallContext.current().getCallingAccount();
    Account owner = _accountMgr.getAccount(securityGroup.getAccountId());
    if (owner == null) {
        throw new InvalidParameterValueException("Unable to find security group owner by id=" + securityGroup.getAccountId());
    }
    // Verify permissions
    _accountMgr.checkAccess(caller, null, true, securityGroup);
    Long domainId = owner.getDomainId();
    if (protocol == null) {
        protocol = NetUtils.ALL_PROTO;
    }
    if (cidrList != null) {
        for (String cidr : cidrList) {
            if (!NetUtils.isValidCIDR(cidr)) {
                throw new InvalidParameterValueException("Invalid cidr " + cidr);
            }
        }
    }
    if (!NetUtils.isValidSecurityGroupProto(protocol)) {
        throw new InvalidParameterValueException("Invalid protocol " + protocol);
    }
    if ("icmp".equalsIgnoreCase(protocol)) {
        if ((icmpType == null) || (icmpCode == null)) {
            throw new InvalidParameterValueException("Invalid ICMP type/code specified, icmpType = " + icmpType + ", icmpCode = " + icmpCode);
        }
        if (icmpType == -1 && icmpCode != -1) {
            throw new InvalidParameterValueException("Invalid icmp code");
        }
        if (icmpType != -1 && icmpCode == -1) {
            throw new InvalidParameterValueException("Invalid icmp code: need non-negative icmp code ");
        }
        if (icmpCode > 255 || icmpType > 255 || icmpCode < -1 || icmpType < -1) {
            throw new InvalidParameterValueException("Invalid icmp type/code ");
        }
        startPortOrType = icmpType;
        endPortOrCode = icmpCode;
    } else if (protocol.equals(NetUtils.ALL_PROTO)) {
        if ((startPort != null) || (endPort != null)) {
            throw new InvalidParameterValueException("Cannot specify startPort or endPort without specifying protocol");
        }
        startPortOrType = 0;
        endPortOrCode = 0;
    } else {
        if ((startPort == null) || (endPort == null)) {
            throw new InvalidParameterValueException("Invalid port range specified, startPort = " + startPort + ", endPort = " + endPort);
        }
        if (startPort == 0 && endPort == 0) {
            endPort = 65535;
        }
        if (startPort > endPort) {
            throw new InvalidParameterValueException("Invalid port range " + startPort + ":" + endPort);
        }
        if (startPort > 65535 || endPort > 65535 || startPort < -1 || endPort < -1) {
            throw new InvalidParameterValueException("Invalid port numbers " + startPort + ":" + endPort);
        }
        if (startPort < 0 || endPort < 0) {
            throw new InvalidParameterValueException("Invalid port range " + startPort + ":" + endPort);
        }
        startPortOrType = startPort;
        endPortOrCode = endPort;
    }
    protocol = protocol.toLowerCase();
    List<SecurityGroupVO> authorizedGroups = new ArrayList<SecurityGroupVO>();
    if (groupList != null) {
        Collection userGroupCollection = groupList.values();
        Iterator iter = userGroupCollection.iterator();
        while (iter.hasNext()) {
            HashMap userGroup = (HashMap) iter.next();
            String group = (String) userGroup.get("group");
            String authorizedAccountName = (String) userGroup.get("account");
            if ((group == null) || (authorizedAccountName == null)) {
                throw new InvalidParameterValueException("Invalid user group specified, fields 'group' and 'account' cannot be null, please specify groups in the form:  userGroupList[0].group=XXX&userGroupList[0].account=YYY");
            }
            Account authorizedAccount = _accountDao.findActiveAccount(authorizedAccountName, domainId);
            if (authorizedAccount == null) {
                throw new InvalidParameterValueException("Nonexistent account: " + authorizedAccountName + " when trying to authorize security group rule  for " + securityGroupId + ":" + protocol + ":" + startPortOrType + ":" + endPortOrCode);
            }
            SecurityGroupVO groupVO = _securityGroupDao.findByAccountAndName(authorizedAccount.getId(), group);
            if (groupVO == null) {
                throw new InvalidParameterValueException("Nonexistent group " + group + " for account " + authorizedAccountName + "/" + domainId + " is given, unable to authorize security group rule.");
            }
            // Check permissions
            if (domainId != groupVO.getDomainId()) {
                throw new PermissionDeniedException("Can't add security group id=" + groupVO.getDomainId() + " as it belongs to different domain");
            }
            authorizedGroups.add(groupVO);
        }
    }
    final Set<SecurityGroupVO> authorizedGroups2 = new TreeSet<SecurityGroupVO>(new SecurityGroupVOComparator());
    // Ensure we don't re-lock the same row
    authorizedGroups2.addAll(authorizedGroups);
    final Integer startPortOrTypeFinal = startPortOrType;
    final Integer endPortOrCodeFinal = endPortOrCode;
    final String protocolFinal = protocol;
    List<SecurityGroupRuleVO> newRules = Transaction.execute(new TransactionCallback<List<SecurityGroupRuleVO>>() {

        @Override
        public List<SecurityGroupRuleVO> doInTransaction(TransactionStatus status) {
            // Prevents other threads/management servers from creating duplicate security rules
            SecurityGroup securityGroup = _securityGroupDao.acquireInLockTable(securityGroupId);
            if (securityGroup == null) {
                s_logger.warn("Could not acquire lock on network security group: id= " + securityGroupId);
                return null;
            }
            List<SecurityGroupRuleVO> newRules = new ArrayList<SecurityGroupRuleVO>();
            try {
                for (final SecurityGroupVO ngVO : authorizedGroups2) {
                    final Long ngId = ngVO.getId();
                    // Don't delete the referenced group from under us
                    if (ngVO.getId() != securityGroup.getId()) {
                        final SecurityGroupVO tmpGrp = _securityGroupDao.lockRow(ngId, false);
                        if (tmpGrp == null) {
                            s_logger.warn("Failed to acquire lock on security group: " + ngId);
                            throw new ConcurrentAccessException("Failed to acquire lock on security group: " + ngId);
                        }
                    }
                    SecurityGroupRuleVO securityGroupRule = _securityGroupRuleDao.findByProtoPortsAndAllowedGroupId(securityGroup.getId(), protocolFinal, startPortOrTypeFinal, endPortOrCodeFinal, ngVO.getId());
                    if ((securityGroupRule != null) && (securityGroupRule.getRuleType() == ruleType)) {
                        // rule already exists.
                        continue;
                    }
                    securityGroupRule = new SecurityGroupRuleVO(ruleType, securityGroup.getId(), startPortOrTypeFinal, endPortOrCodeFinal, protocolFinal, ngVO.getId());
                    securityGroupRule = _securityGroupRuleDao.persist(securityGroupRule);
                    newRules.add(securityGroupRule);
                }
                if (cidrList != null) {
                    for (String cidr : cidrList) {
                        SecurityGroupRuleVO securityGroupRule = _securityGroupRuleDao.findByProtoPortsAndCidr(securityGroup.getId(), protocolFinal, startPortOrTypeFinal, endPortOrCodeFinal, cidr);
                        if ((securityGroupRule != null) && (securityGroupRule.getRuleType() == ruleType)) {
                            continue;
                        }
                        securityGroupRule = new SecurityGroupRuleVO(ruleType, securityGroup.getId(), startPortOrTypeFinal, endPortOrCodeFinal, protocolFinal, cidr);
                        securityGroupRule = _securityGroupRuleDao.persist(securityGroupRule);
                        newRules.add(securityGroupRule);
                    }
                }
                if (s_logger.isDebugEnabled()) {
                    s_logger.debug("Added " + newRules.size() + " rules to security group " + securityGroup.getName());
                }
                return newRules;
            } catch (Exception e) {
                s_logger.warn("Exception caught when adding security group rules ", e);
                throw new CloudRuntimeException("Exception caught when adding security group rules", e);
            } finally {
                if (securityGroup != null) {
                    _securityGroupDao.releaseFromLockTable(securityGroup.getId());
                }
            }
        }
    });
    try {
        final ArrayList<Long> affectedVms = new ArrayList<Long>();
        affectedVms.addAll(_securityGroupVMMapDao.listVmIdsBySecurityGroup(securityGroup.getId()));
        scheduleRulesetUpdateToHosts(affectedVms, true, null);
    } catch (Exception e) {
        s_logger.debug("can't update rules on host, ignore", e);
    }
    return newRules;
}
Also used : Account(com.cloud.user.Account) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) TransactionStatus(com.cloud.utils.db.TransactionStatus) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) TreeSet(java.util.TreeSet) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) Iterator(java.util.Iterator) ArrayList(java.util.ArrayList) List(java.util.List) AgentUnavailableException(com.cloud.exception.AgentUnavailableException) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) OperationTimedoutException(com.cloud.exception.OperationTimedoutException) ConcurrentModificationException(java.util.ConcurrentModificationException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) ResourceInUseException(com.cloud.exception.ResourceInUseException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ConcurrentAccessException(javax.ejb.ConcurrentAccessException) ConfigurationException(javax.naming.ConfigurationException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) Collection(java.util.Collection) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) ConcurrentAccessException(javax.ejb.ConcurrentAccessException)

Example 75 with PermissionDeniedException

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

the class QuotaServiceImpl method getQuotaUsage.

@Override
public List<QuotaUsageVO> getQuotaUsage(Long accountId, String accountName, Long domainId, Integer usageType, Date startDate, Date endDate) {
    // if accountId is not specified, use accountName and domainId
    if ((accountId == null) && (accountName != null) && (domainId != null)) {
        Account userAccount = null;
        Account caller = CallContext.current().getCallingAccount();
        if (_domainDao.isChildDomain(caller.getDomainId(), domainId)) {
            Filter filter = new Filter(AccountVO.class, "id", Boolean.FALSE, null, null);
            List<AccountVO> accounts = _accountDao.listAccounts(accountName, domainId, filter);
            if (!accounts.isEmpty()) {
                userAccount = accounts.get(0);
            }
            if (userAccount != null) {
                accountId = userAccount.getId();
            } else {
                throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain " + domainId);
            }
        } else {
            throw new PermissionDeniedException("Invalid Domain Id or Account");
        }
    }
    if (startDate.after(endDate)) {
        throw new InvalidParameterValueException("Incorrect Date Range. Start date: " + startDate + " is after end date:" + endDate);
    }
    if (endDate.after(_respBldr.startOfNextDay())) {
        throw new InvalidParameterValueException("Incorrect Date Range. End date:" + endDate + " should not be in future. ");
    }
    Date adjustedEndDate = computeAdjustedTime(endDate);
    Date adjustedStartDate = computeAdjustedTime(startDate);
    if (s_logger.isDebugEnabled()) {
        s_logger.debug("Getting quota records for account: " + accountId + ", domainId: " + domainId + ", between " + adjustedStartDate + " and " + adjustedEndDate);
    }
    return _quotaUsageDao.findQuotaUsage(accountId, domainId, usageType, adjustedStartDate, adjustedEndDate);
}
Also used : Account(com.cloud.user.Account) Filter(com.cloud.utils.db.Filter) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) QuotaAccountVO(org.apache.cloudstack.quota.vo.QuotaAccountVO) AccountVO(com.cloud.user.AccountVO) Date(java.util.Date)

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