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;
}
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);
}
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;
}
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);
}
use of com.cloud.exception.PermissionDeniedException in project cloudstack by apache.
the class ConfigurationManagerImpl method createVlanAndPublicIpRange.
@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_VLAN_IP_RANGE_CREATE, eventDescription = "creating vlan ip range", async = false)
public Vlan createVlanAndPublicIpRange(final CreateVlanIpRangeCmd cmd) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, ResourceAllocationException {
Long zoneId = cmd.getZoneId();
final Long podId = cmd.getPodId();
final String startIP = cmd.getStartIp();
String endIP = cmd.getEndIp();
final String newVlanGateway = cmd.getGateway();
final String newVlanNetmask = cmd.getNetmask();
String vlanId = cmd.getVlan();
// TODO decide if we should be forgiving or demand a valid and complete URI
if (!(vlanId == null || "".equals(vlanId) || vlanId.startsWith(BroadcastDomainType.Vlan.scheme()))) {
vlanId = BroadcastDomainType.Vlan.toUri(vlanId).toString();
}
final Boolean forVirtualNetwork = cmd.isForVirtualNetwork();
Long networkId = cmd.getNetworkID();
Long physicalNetworkId = cmd.getPhysicalNetworkId();
final String accountName = cmd.getAccountName();
final Long projectId = cmd.getProjectId();
final Long domainId = cmd.getDomainId();
final String startIPv6 = cmd.getStartIpv6();
String endIPv6 = cmd.getEndIpv6();
final String ip6Gateway = cmd.getIp6Gateway();
final String ip6Cidr = cmd.getIp6Cidr();
Account vlanOwner = null;
final boolean ipv4 = startIP != null;
final boolean ipv6 = startIPv6 != null;
if (!ipv4 && !ipv6) {
throw new InvalidParameterValueException("StartIP or StartIPv6 is missing in the parameters!");
}
if (ipv4) {
// if end ip is not specified, default it to startIp
if (endIP == null && startIP != null) {
endIP = startIP;
}
}
if (ipv6) {
// if end ip is not specified, default it to startIp
if (endIPv6 == null && startIPv6 != null) {
endIPv6 = startIPv6;
}
}
if (projectId != null) {
if (accountName != null) {
throw new InvalidParameterValueException("Account and projectId are mutually exclusive");
}
final Project project = _projectMgr.getProject(projectId);
if (project == null) {
throw new InvalidParameterValueException("Unable to find project by id " + projectId);
}
vlanOwner = _accountMgr.getAccount(project.getProjectAccountId());
if (vlanOwner == null) {
throw new InvalidParameterValueException("Please specify a valid projectId");
}
}
Domain domain = null;
if (accountName != null && domainId != null) {
vlanOwner = _accountDao.findActiveAccount(accountName, domainId);
if (vlanOwner == null) {
throw new InvalidParameterValueException("Please specify a valid account.");
} else if (vlanOwner.getId() == Account.ACCOUNT_ID_SYSTEM) {
// by default vlan is dedicated to system account
vlanOwner = null;
}
} else if (domainId != null) {
domain = _domainDao.findById(domainId);
if (domain == null) {
throw new InvalidParameterValueException("Please specify a valid domain id");
}
}
// Verify that network exists
Network network = null;
if (networkId != null) {
network = _networkDao.findById(networkId);
if (network == null) {
throw new InvalidParameterValueException("Unable to find network by id " + networkId);
} else {
zoneId = network.getDataCenterId();
physicalNetworkId = network.getPhysicalNetworkId();
}
} else if (ipv6) {
throw new InvalidParameterValueException("Only support IPv6 on extending existed network");
}
// Verify that zone exists
final DataCenterVO zone = _zoneDao.findById(zoneId);
if (zone == null) {
throw new InvalidParameterValueException("Unable to find zone by id " + zoneId);
}
if (ipv6) {
if (network.getGuestType() != GuestType.Shared || zone.isSecurityGroupEnabled()) {
throw new InvalidParameterValueException("Only support IPv6 on extending existed share network without SG");
}
}
// verify that physical network exists
PhysicalNetworkVO pNtwk = null;
if (physicalNetworkId != null) {
pNtwk = _physicalNetworkDao.findById(physicalNetworkId);
if (pNtwk == null) {
throw new InvalidParameterValueException("Unable to find Physical Network with id=" + physicalNetworkId);
}
if (zoneId == null) {
zoneId = pNtwk.getDataCenterId();
}
} else {
if (zoneId == null) {
throw new InvalidParameterValueException("");
}
// deduce physicalNetworkFrom Zone or Network.
if (network != null && network.getPhysicalNetworkId() != null) {
physicalNetworkId = network.getPhysicalNetworkId();
} else {
if (forVirtualNetwork) {
// default physical network with public traffic in the zone
physicalNetworkId = _networkModel.getDefaultPhysicalNetworkByZoneAndTrafficType(zoneId, TrafficType.Public).getId();
} else {
if (zone.getNetworkType() == DataCenter.NetworkType.Basic) {
// default physical network with guest traffic in the
// zone
physicalNetworkId = _networkModel.getDefaultPhysicalNetworkByZoneAndTrafficType(zoneId, TrafficType.Guest).getId();
} else if (zone.getNetworkType() == DataCenter.NetworkType.Advanced) {
if (zone.isSecurityGroupEnabled()) {
physicalNetworkId = _networkModel.getDefaultPhysicalNetworkByZoneAndTrafficType(zoneId, TrafficType.Guest).getId();
} else {
throw new InvalidParameterValueException("Physical Network Id is null, please provide the Network id for Direct vlan creation ");
}
}
}
}
}
// Check if zone is enabled
final Account caller = CallContext.current().getCallingAccount();
if (Grouping.AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(caller.getId())) {
throw new PermissionDeniedException("Cannot perform this operation, Zone is currently disabled: " + zoneId);
}
if (zone.isSecurityGroupEnabled() && zone.getNetworkType() != DataCenter.NetworkType.Basic && forVirtualNetwork) {
throw new InvalidParameterValueException("Can't add virtual ip range into a zone with security group enabled");
}
// Untagged, try to locate default networks
if (forVirtualNetwork) {
if (network == null) {
// find default public network in the zone
networkId = _networkModel.getSystemNetworkByZoneAndTrafficType(zoneId, TrafficType.Public).getId();
network = _networkModel.getNetwork(networkId);
} else if (network.getGuestType() != null || network.getTrafficType() != TrafficType.Public) {
throw new InvalidParameterValueException("Can't find Public network by id=" + networkId);
}
} else {
if (network == null) {
if (zone.getNetworkType() == DataCenter.NetworkType.Basic) {
networkId = _networkModel.getExclusiveGuestNetwork(zoneId).getId();
network = _networkModel.getNetwork(networkId);
} else {
network = _networkModel.getNetworkWithSecurityGroupEnabled(zoneId);
if (network == null) {
throw new InvalidParameterValueException("Nework id is required for Direct vlan creation ");
}
networkId = network.getId();
zoneId = network.getDataCenterId();
}
} else if (network.getGuestType() == null || network.getGuestType() == Network.GuestType.Isolated && _ntwkOffServiceMapDao.areServicesSupportedByNetworkOffering(network.getNetworkOfferingId(), Service.SourceNat)) {
throw new InvalidParameterValueException("Can't create direct vlan for network id=" + networkId + " with type: " + network.getGuestType());
}
}
Pair<Boolean, Pair<String, String>> sameSubnet = null;
// Can add vlan range only to the network which allows it
if (!network.getSpecifyIpRanges()) {
throw new InvalidParameterValueException("Network " + network + " doesn't support adding ip ranges");
}
if (zone.getNetworkType() == DataCenter.NetworkType.Advanced) {
if (network.getTrafficType() == TrafficType.Guest) {
if (network.getGuestType() != GuestType.Shared) {
throw new InvalidParameterValueException("Can execute createVLANIpRanges on shared guest network, but type of this guest network " + network.getId() + " is " + network.getGuestType());
}
final List<VlanVO> vlans = _vlanDao.listVlansByNetworkId(network.getId());
if (vlans != null && vlans.size() > 0) {
final VlanVO vlan = vlans.get(0);
if (vlanId == null || vlanId.contains(Vlan.UNTAGGED)) {
vlanId = vlan.getVlanTag();
} else if (!NetUtils.isSameIsolationId(vlan.getVlanTag(), vlanId)) {
throw new InvalidParameterValueException("there is already one vlan " + vlan.getVlanTag() + " on network :" + +network.getId() + ", only one vlan is allowed on guest network");
}
}
sameSubnet = validateIpRange(startIP, endIP, newVlanGateway, newVlanNetmask, vlans, ipv4, ipv6, ip6Gateway, ip6Cidr, startIPv6, endIPv6, network);
}
} else if (network.getTrafficType() == TrafficType.Management) {
throw new InvalidParameterValueException("Cannot execute createVLANIpRanges on management network");
} else if (zone.getNetworkType() == NetworkType.Basic) {
final List<VlanVO> vlans = _vlanDao.listVlansByNetworkId(network.getId());
sameSubnet = validateIpRange(startIP, endIP, newVlanGateway, newVlanNetmask, vlans, ipv4, ipv6, ip6Gateway, ip6Cidr, startIPv6, endIPv6, network);
}
if (zoneId == null || ipv6 && (ip6Gateway == null || ip6Cidr == null)) {
throw new InvalidParameterValueException("Gateway, netmask and zoneId have to be passed in for virtual and direct untagged networks");
}
if (forVirtualNetwork) {
if (vlanOwner != null) {
final long accountIpRange = NetUtils.ip2Long(endIP) - NetUtils.ip2Long(startIP) + 1;
// check resource limits
_resourceLimitMgr.checkResourceLimit(vlanOwner, ResourceType.public_ip, accountIpRange);
}
}
// Check if the IP range overlaps with the private ip
if (ipv4) {
checkOverlapPrivateIpRange(zoneId, startIP, endIP);
}
return commitVlan(zoneId, podId, startIP, endIP, newVlanGateway, newVlanNetmask, vlanId, forVirtualNetwork, networkId, physicalNetworkId, startIPv6, endIPv6, ip6Gateway, ip6Cidr, domain, vlanOwner, network, sameSubnet);
}
Aggregations