Search in sources :

Example 1 with RequestLimitException

use of com.cloud.exception.RequestLimitException 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 2 with RequestLimitException

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

the class ApiRateLimitServiceImpl method checkAccess.

@Override
public boolean checkAccess(User user, String apiCommandName) throws PermissionDeniedException {
    // check if api rate limiting is enabled or not
    if (!enabled) {
        return true;
    }
    Long accountId = user.getAccountId();
    Account account = _accountService.getAccount(accountId);
    if (_accountService.isRootAdmin(account.getId())) {
        // no API throttling on root admin
        return true;
    }
    StoreEntry entry = _store.get(accountId);
    if (entry == null) {
        /* Populate the entry, thus unlocking any underlying mutex */
        entry = _store.create(accountId, timeToLive);
    }
    /* Increment the client count and see whether we have hit the maximum allowed clients yet. */
    int current = entry.incrementAndGet();
    if (current <= maxAllowed) {
        s_logger.trace("account (" + account.getAccountId() + "," + account.getAccountName() + ") has current count = " + current);
        return true;
    } else {
        long expireAfter = entry.getExpireDuration();
        // for this exception, we can just show the same message to user and admin users.
        String msg = "The given user has reached his/her account api limit, please retry after " + expireAfter + " ms.";
        s_logger.warn(msg);
        throw new RequestLimitException(msg);
    }
}
Also used : Account(com.cloud.user.Account) RequestLimitException(com.cloud.exception.RequestLimitException)

Aggregations

RequestLimitException (com.cloud.exception.RequestLimitException)2 Account (com.cloud.user.Account)2 AccountLimitException (com.cloud.exception.AccountLimitException)1 CloudAuthenticationException (com.cloud.exception.CloudAuthenticationException)1 InsufficientCapacityException (com.cloud.exception.InsufficientCapacityException)1 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)1 PermissionDeniedException (com.cloud.exception.PermissionDeniedException)1 ResourceAllocationException (com.cloud.exception.ResourceAllocationException)1 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)1 User (com.cloud.user.User)1 UserAccount (com.cloud.user.UserAccount)1 TransactionLegacy (com.cloud.utils.db.TransactionLegacy)1 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)1 ExceptionProxyObject (com.cloud.utils.exception.ExceptionProxyObject)1 IOException (java.io.IOException)1 InterruptedIOException (java.io.InterruptedIOException)1 URISyntaxException (java.net.URISyntaxException)1 ParseException (java.text.ParseException)1 ArrayList (java.util.ArrayList)1 Date (java.util.Date)1