9 Common API Threats, And How To Avoid Them

Posted in

By their very nature, APIs enable access to large amounts of data, potentially sensitive customer data, while bypassing browser precautions. No longer is it sufficient to focus on SQL injection and XSS issues. Instead, you should be concerned with bad actors who can paginate through all of your customers’ records and their associated data.

Typical prevention mechanisms like Captchas and browser fingerprinting won’t work, since by design, APIs must handle a vast number of API calls for each consumer. So, where do you start? The first thing is to put yourself in the shoes of a hacker. Then, instrument your APIs to detect and block common attacks along with unknowns for zero-day exploits.

Below, we’ll cover nine of the most common API threats, and discuss how to avoid them altogether. Some of these are on the OWASP Security API list, but not all.

1. Pagination Attacks

Most APIs provide access to resources that are lists of entities such as /users or /widgets. A client such as a browser would typically filter and paginate through this list to limit the number of items returned to a client like so:

First Call: GET /items?skip=0&take=10

Second Call: GET /items?skip=10&take=10

However, if that entity has any PII or other information, then a hacker could scrape that endpoint to get a dump of all entities in your database. This could be most dangerous if those entities accidentally exposed PII or other sensitive information, but could also be hazardous in providing competitors or others with adoption and usage stats for your business or give scammers a way to access large email lists. For example, see how Venmo data was scraped here.

A naive protection mechanism would be to check the take count and throw an error if greater than 100 or 1000. The problem with this is two-fold:

  1. For data APIs, legitimate customers may need to fetch and sync many records via cron jobs. Artificially small pagination limits can force your API to be very chatty, decreasing overall throughput. Max limits are to ensure memory and scalability requirements are met (and prevent certain DDoS attacks), not to guarantee security.
  2. This offers zero protection to a hacker that writes a simple script that sleeps a random delay between repeated accesses.
skip = 0
while True:
    response = requests.post('https://api.acmeinc.com/widgets?take=10&skip=' + skip),
                      headers={'Authorization': 'Bearer' + ' ' + sys.argv[1]})
    print("Fetched 10 items")
    skip += 10

How to Secure Against Pagination Attacks

To secure against pagination attacks, you should track how many items of a single resource are accessed within a certain time period for each user or API key rather than just at the request level. By tracking API resource access at the user level, you can block a user or API key once they hit a threshold, such as “touched 1,000,000 items in one hour.” This is dependent on your API use case and can even be dependent on their subscription with you. Like a Captcha, this can slow down the speed that a hacker can exploit your API if they have to create a new user account manually to create a new API key.

2. Insecure API Key Generation

Most APIs are protected by some sort of API key or JWT (JSON Web Token). This provides a natural way to track and protect your API as API security tools can detect abnormal API behavior and block access to an API key automatically. However, hackers will want to outsmart these mechanisms by generating and using a large pool of API keys from a large number of users — just like a web hacker would use a large pool of IP addresses to circumvent DDoS protection.

How to Secure Against API Key Pools

The easiest way to secure against these types of attacks is by requiring a human to sign up for your service and generate API keys. Bot traffic can be prevented with things like Captcha and 2-Factor Authentication.

Unless there is a legitimate business case, new users who sign up for your service should not have the ability to generate API keys programmatically. Instead, only trusted customers should have the ability to generate API keys programmatically. Go one step further and ensure any anomaly detection for abnormal behavior is done at the user and account level, not just for each API key.

3. Accidental Key Exposure

APIs are often used in a way that increases the probability credentials are leaked:

  1. APIs are expected to be accessed over indefinite time periods, which increases the probability that a hacker obtains a valid API key that’s not expired. You save that API key in a server environment variable and forget about it. This is a drastic contrast to a user logging into an interactive website where the session expires after a short duration.
  2. The consumer of an API has direct access to the credentials, such as when debugging via Postman or CURL. It only takes a single developer to accidentally copy/paste the CURL command containing the API key into a public forum like in GitHub Issues or Stack Overflow.
  3. API keys are usually bearer tokens without requiring any other identifying information. APIs cannot leverage things like one-time-use tokens or 2-factor authentication.

If a key is exposed due to user error, one may think you as the API provider hold the blame. However, security is all about reducing surface area and risk. Treat your customer’s data as if it’s your own; help them by adding guards that prevent accidental key exposure.

How to Prevent Accidental Key Exposure

The easiest way to prevent key exposure is by leveraging two tokens rather than one. A refresh token is stored as an environment variable and can only be used to generate short-lived access tokens. Unlike the refresh token, these short-lived tokens can access the resources but are time-limited, such as in hours or days.

The customer will store the refresh token with other API keys. Then your SDK will generate access tokens on SDK init or when the last access token expires. If a CURL command gets pasted into a GitHub issue, then a hacker would need to use it within hours reducing the attack vector (unless it was the actual refresh token which is a low probability).

4. Exposure to DDoS Attacks

APIs open up entirely new business models where customers can access your API platform programmatically. However, this can make DDoS protection tricky. Most DDoS protection is designed to absorb and reject a large number of requests from bad actors during attacks. Yet, they still need to let through the good ones. This process requires fingerprinting the HTTP requests to check against what looks like bot traffic. However, this is much harder for API products as all traffic looks like bot traffic and does not come from a browser where things like cookies are present.

Stopping DDoS Attacks

The magical part about APIs is almost every access requires an API Key. Suppose a request doesn’t have an API key. In that case, you can automatically reject it, which is lightweight on your servers (Ensure authentication is short-circuited very early before later middleware like request JSON parsing).

So then how do you handle authenticated requests? The easiest is to leverage rate limit counters for each API key, such as handling X requests per minute and reject those above the threshold with a 429 HTTP response. There are a variety of algorithms to do this leaky bucket and fixed window counters.

5. Incorrect Server Security

APIs are no different than web servers when it comes to good server hygiene. Data can be leaked due to misconfigured SSL certificates or allowing non-HTTPS traffic. For modern applications, there is very little reason to accept non-HTTPS requests, but a customer could mistakenly issue a non HTTP request from their application or CURL exposing the API key. APIs do not have the protection of a browser, so things like HSTS or redirect to HTTPS offer no protection.

How to Ensure Proper SSL

Test your SSL implementation over at Qualys SSL Test or using a similar tool. You should also block all non-HTTP requests which can be done within your load balancer. You should also remove any HTTP headers and scrub any error messages that leak implementation details. If your API is used only by your own apps or can only be accessed server-side, then review the Authoritative guide to Cross-Origin Resource Sharing for REST APIs.

6. Incorrect Caching Headers

APIs provide access to dynamic data that’s scoped to each API key. Any caching implementation should have the ability to scope to an API key to prevent cross-pollution. Even if you don’t cache anything in your infrastructure, you could expose your customers to security holes. If a customer with a proxy server was using multiple API keys, such as one for development and one for production, they could see cross-pollinated data.

How severe is this? See Twitter’s disclosure of a billing info leak after a data security incident.

How to Ensure No Caching

You should ensure Cache-Control headers are properly configured.

A big gotcha for APIs is that many do not use the standard Authorization header. Instead, they use a custom header like X-Api-Key. Caching servers do not have knowledge of this request being authenticated and thus chooses to cache the request.

app.use((req, res, next) => {
  res.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate');
  res.setHeader('Pragma', 'no-cache');
  // ...

7. Insufficient Logging & Monitoring

Insufficient logging & monitoring is an OWASP top 10 API Security item. Most breach studies demonstrate the time to detect a data breach is over 200 days. If you don’t have proper API logging and monitoring in place, attackers can continue using the same vulnerability, or even
probe for more vulnerabilities.

How to Properly Add API Logging

You should ensure your API logging not only tracks the API requests themselves but is also tied back to users for user behavior analytics and stored for at least a year. These systems should be protected to ensure data cannot be accidentally deleted or retired early.

GDPR and CCPA provide exceptions for API audit logs for security purposes. Solutions from some companies provide a full suite of API monitoring and analytics for API products and can get started in just a few minutes:

8. Insecure Internal Endpoints

The same API service may have endpoints that are used both externally and externally. Just because an endpoint is not documented does not mean a hacker cannot call it. Besides securing with an authentication and authorization scheme, you should ensure these endpoints are not exposed to the public Internet at all, which can be done within your load balancer or API gateway. This helps by providing multiple levels of security, a common strategy in prevention.

9. Not Handling Authorization

While most API developers will add a global Authentication scheme such as API keys or OAuth to verify who the person is, it’s harder to implement Authorization. It’s also required and separate from Authentication. Authorization involves checking whether this person (who is already identified) can access a particular resource. This can be done via API scopes, checking against a tenant id or user id, among other things.

Because it’s specific to your application logic and is not always cross-cutting, Authorization can be an area developers forget about. Unless your object identifiers have enough entropy, a hacker could easily test different ids through iteration. This is especially true for SQL databases that increment the id on insertion.

How to Fix Authorization

Ensure the authenticated user is authorized to access all resources that are required to generate the API response. This may involve checking against a user id or access control lists (ACL) that’s linked to the objects in question. More info on how to handle Authorization can be found here: Steps to building Authentication and Authorization for RESTful APIs