Search in sources :

Example 36 with PermissionDeniedException

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

the class UserVmManagerTest method testMoveVmToUser2.

// Test Move VM b/w accounts where caller doesn't have access to the old or new account
@Test(expected = PermissionDeniedException.class)
public void testMoveVmToUser2() throws Exception {
    AssignVMCmd cmd = new AssignVMCmd();
    Class<?> _class = cmd.getClass();
    Field virtualmachineIdField = _class.getDeclaredField("virtualMachineId");
    virtualmachineIdField.setAccessible(true);
    virtualmachineIdField.set(cmd, 1L);
    Field accountNameField = _class.getDeclaredField("accountName");
    accountNameField.setAccessible(true);
    accountNameField.set(cmd, "account");
    Field domainIdField = _class.getDeclaredField("domainId");
    domainIdField.setAccessible(true);
    domainIdField.set(cmd, 1L);
    // caller is of type 0
    Account caller = new AccountVO("testaccount", 1, "networkdomain", (short) 1, UUID.randomUUID().toString());
    UserVO user = new UserVO(1, "testuser", "password", "firstname", "lastName", "email", "timezone", UUID.randomUUID().toString(), User.Source.UNKNOWN);
    Account oldAccount = new AccountVO("testaccount", 1, "networkdomain", (short) 0, UUID.randomUUID().toString());
    Account newAccount = new AccountVO("testaccount", 1, "networkdomain", (short) 1, UUID.randomUUID().toString());
    UserVmVO vm = new UserVmVO(10L, "test", "test", 1L, HypervisorType.Any, 1L, false, false, 1L, 1L, 1, 5L, "test", "test", 1L);
    vm.setState(VirtualMachine.State.Stopped);
    when(_vmDao.findById(anyLong())).thenReturn(vm);
    when(_accountService.getActiveAccountById(anyLong())).thenReturn(oldAccount);
    when(_accountMgr.finalizeOwner(any(Account.class), anyString(), anyLong(), anyLong())).thenReturn(newAccount);
    doThrow(new PermissionDeniedException("Access check failed")).when(_accountMgr).checkAccess(any(Account.class), any(AccessType.class), any(Boolean.class), any(ControlledEntity.class));
    CallContext.register(user, caller);
    when(_accountMgr.isRootAdmin(anyLong())).thenReturn(true);
    try {
        _userVmMgr.moveVMToUser(cmd);
    } finally {
        CallContext.unregister();
    }
}
Also used : Field(java.lang.reflect.Field) Account(com.cloud.user.Account) UserVO(com.cloud.user.UserVO) ControlledEntity(org.apache.cloudstack.acl.ControlledEntity) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) AssignVMCmd(org.apache.cloudstack.api.command.admin.vm.AssignVMCmd) Matchers.anyBoolean(org.mockito.Matchers.anyBoolean) AccountVO(com.cloud.user.AccountVO) AccessType(org.apache.cloudstack.acl.SecurityChecker.AccessType) Test(org.junit.Test)

Example 37 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 38 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 39 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)

Example 40 with PermissionDeniedException

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

the class CreateSnapshotCmd method getEntityOwnerId.

@Override
public long getEntityOwnerId() {
    Volume volume = _entityMgr.findById(Volume.class, getVolumeId());
    if (volume == null) {
        throw new InvalidParameterValueException("Unable to find volume by id=" + volumeId);
    }
    Account account = _accountService.getAccount(volume.getAccountId());
    //Can create templates for enabled projects/accounts only
    if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) {
        Project project = _projectService.findByProjectAccountId(volume.getAccountId());
        if (project.getState() != Project.State.Active) {
            throw new PermissionDeniedException("Can't add resources to the project id=" + project.getId() + " in state=" + project.getState() + " as it's no longer active");
        }
    } else if (account.getState() == Account.State.disabled) {
        throw new PermissionDeniedException("The owner of template is disabled: " + account);
    }
    return volume.getAccountId();
}
Also used : Account(com.cloud.user.Account) Project(com.cloud.projects.Project) Volume(com.cloud.storage.Volume) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException)

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