API Security — Introduction

Siddiquimohammad
11 min readMar 16, 2024

--

  • APIs are the entry point for accessing an organization’s functions and data.
  • However, exposing an API to unintended parties can cause considerable damages to organization’s digital assets and could result in leakage of sensitive information.
  • Therefore, security aspects related to APIs are a main concern when implementing a microservice application.
  • If you want your application to be secure , make sure the APIs are secure

What we will discuss ?

- Need for API security

- Types of APIs

- Common API threats

1. Need for API security

  • API security refers to the practices and systems in place to protect application programming interfaces (APIs) from unauthorized access, modification, or exploitation.
  • API security is at the crossroads of three main areas of security:
  • Attacks targeting APIs are one of the most serious security threats facing businesses, as they provide direct access to sensitive data and functionalities. And attackers have become aware of the popularity of APIs and the existence of critical vulnerabilities in these interfaces. The problem is that web applications remain the primary target of attacks (90% according to Verizon*) and APIs now represent 90% of the attack surface of web applications. Thus, APIs have become one of the main attack vectors, with devastating financial consequences for the companies that bear the costs.
  • Furthermore, because APIs use web technologies, an API developer will face common vulnerabilities within this ecosystem. Most of the risks associated with web applications are applicable to APIs, but due to their nature, they extend the attack surface and face unique risk factors. While web applications are designed to provide access to a specific user interface and expose specific functionality from the back-end, APIs provide a much more flexible channel to the back-end, in terms of the amount of information that can be retrieved from the servers. Indeed, APIs facilitate the transfer of large amounts of data much more easily than web applications can.
  • An API can be called multiple times to generate a DoS attack. In addition, firewalls, antivirus, and other technical security solutions cannot block attacks that exploit specific vulnerabilities in APIs. They cannot detect injection attacks, or logical attacks on parameters or workflows.
  • Similarly, vulnerability scanners used for automated security audits cannot identify most of these vulnerabilities — especially the “VERY” common logical vulnerabilities in APIs, unlike penetration testing, which follows a proven methodology that includes a “VERY” valuable vulnerability exploitation phase, enabling not only the identification of other vulnerabilities, but also the assessment of their impacts and potential side effects.
  • Security should therefore be an essential part of any organization's API development strategy
Source : https://university.apisec.ai/

2. Types of APIs

  • API architecture refers to the structure and design principles used in developing application programming interfaces.
  • Common types of API architecture include REST, SOAP, and RPC

REST

REST is Representational State Transfer Architecture, a commonly adapted API approach for a web application.

It provides a flexible client-server system to receive and respond to users’ requests.

The communication protocol used is HTTP to request and respond to the user.

JavaScript Object Notation is used to deliver the responses to the users.

It does not store any requests and responses. Instead, it responds to each incoming request.

SOAP

SOAP is a Simple Object Access Protocol that is highly structured with defined standards.

It is the most secure API and is used for critical applications.

It is accessible to any communication protocol and uses XML to encode information.

RPC

RPC is a Remote Procedural Call that is used in basic internal processes.

It uses both JSON and XML to respond to requests from the client.

It receives multiple parameters to deliver a response and is used to execute the actions in the servers.

It is a secure and straightforward API to work on remote networks.

### Our discussion will revolve around REST APIs ###

3. Common API threats

Lets understand each threat :

1. Broken Object-Level Authorization

  • Attackers substitute the ID of their own resource in the API call with an ID of a resource belonging to another user.
  • The lack of proper authorization checks allows attackers to access the specified resource.
  • This attack is also known as IDOR (Insecure Direct Object Reference).

Use case

API call parameters use the ID of the resource accessed through the API /api/shop1/financial_info.

Attackers replace the IDs of their resources with a different one which they guessed through /api/shop2/financial_info.

The API does not check permissions and lets the call through.

Problem is aggravated if IDs can be enumerated /api/123/financial_info.

How to prevent

  • Implement authorization checks with user policies and hierarchy.
  • Do not rely on IDs that the client sends. Use IDs stored in the session object instead.
  • Check authorization for each client request to access database.
  • Use random IDs that cannot be guessed (UUIDs).
  • Implement a robust test framework to specifically test for this vulnerability type.

2. Broken User Authentication

Use case

Unprotected APIs that are considered “internal”

Weak authentication that does not follow industry best practices

Weak API keys that are not rotated

Passwords that are weak, plain text, encrypted, poorly hashed, shared, or default passwords

Authentication susceptible to brute force attacks and credential stuffing

Credentials and keys included in URLs

Lack of access token validation (including JWT validation)

Unsigned or weakly signed non-expiring JWTs

How to prevent

  • Check all possible ways to authenticate to all APIs.
  • APIs for password reset and one-time links also allow users to authenticate, and should be protected just as rigorously.
  • Use standard authentication, token generation, password storage, and multi-factor authentication (MFA).
  • Use short-lived access tokens.
  • Authenticate your apps (so you know who is talking to you).
  • Use stricter rate-limiting for authentication, and implement lockout policies and weak password checks.

3. Broken Object Property Level Authorization

  • API endpoints can be vulnerable to attacks based on their data: either they may expose more data than is required for their business purposes (excessive information exposure), or they may inadvertently accept and process more data than they should (mass assignment).

Use case

The API returns full data objects as they are stored in the backend database.

The client application filters the responses and only shows the data that the users really need to see.

Attackers call the API directly and retrieve sensitive data that the UI would filter out.

The API works with the data structures without proper filtering.

Received payload is blindly transformed into an object and stored.

NodeJS:
var user = new User(req.body);
user.save();

Rails:
@user = User.new(params[:user])

Attackers can guess the fields by looking at the GET request data.

How to prevent :

Responses

  • Never rely on the client to filter data!
  • Review all API responses and adapt them to match what the API consumers really need.
  • Carefully define schemas for all the API responses.
  • Do not forget about error responses, define proper schemas as well.
  • Identify all the sensitive data or Personally Identifiable Information (PII), and justify its use using a robust data governance process.

Requests

  • Do not automatically bind incoming data to internal objects.
  • Explicitly define all the parameters and payloads you are expecting.
  • Use the read Only property set to true in object schemas for all properties that can be retrieved through APIs but should never be modified.
  • Precisely define the schemas, types, and patterns you will accept in requests at design time and enforce them at runtime.

4. Unlimited Resource Consumption

  • The API is not protected against an excessive amount of calls or payload sizes.
  • Attackers can use this for Denial of Service (DoS) and authentication flaws like brute force attacks.

Use case

Attackers overload the API by sending more requests than they can handle.

Attackers send requests at a rate exceeding the API’s processing speed, clogging it up.

The size of the requests or some fields in them exceeds what the API can process.

An attacker submits requests with excessively large payloads or complex queries causing the API to hit a bottleneck and drop requests.

How to prevent

  • Apply rate limiting policies to all endpoints.
  • Pay special attention to endpoints related to authentication which are a prime target for hackers.
  • Tailor rate limiting to match what API methods, clients, or addresses need or should be allowed to retrieve.
  • IPs can easily be forged, whenever possible, configure rate limiting on different keys, such as fingerprints, or tokens.
  • Limit payload sizes, and query complexity.
  • Define CPU/memory limits for container and compute resources.
  • Limit the complexity of queries (especially in GraphQL) to prevent excessive computation on the server.
  • Limit the amount of data that can be retrieved by a query by imposing limits on the pagination size, or page counts.
  • Leverage DDoS protections from your cloud provider.

5. Broken Function-Level Authorization

  • The API relies on the client to use user-level or admin-level/privileged APIs as appropriate.
  • Attackers figure out the “hidden” admin API methods and invoke them directly.

Use case

Some administrative functions are exposed as APIs.

Sensitive operations should only be available internally (for example deleting a resource)

Non-privileged users can access these functions without authorization if they know how.

Can be a matter of knowing the URL, or using a different verb or a parameter:

/api/users/v1/user/myinfo

/api/admins/v1/users/all

How to prevent

  • Do not rely on the client to enforce admin access.
  • Apply deny all access by default.
  • Only allow operations to users belonging to the appropriate group or role.
  • Implement properly designed and tested authorization.

6. Unrestricted Access to Sensitive Business Flows

A set of APIs exposes a business flow and an attacker abuses these APIs using automated methods to achieve a malicious intent, such as exfiltrating data or manipulating market or price data.

Use case

An attacker discovers an API to buy a product online and uses automation to bulk purchase all items of a newly released product which they later re-sell.

Real-estate website’s price information can be scraped over time to predict house price trends in an area.

Attackers can use automation to perform actions faster than a human user and gain an unfair advantage on auction sites, or similar.

How to prevent

  • Understand business flows that could be sensitive to abuse and add extra layers of protection to these and ensure authentication is required, using recommended OAuth flows, like authorization_code.
  • Ensure that APIs are fully protected with robust rate-limiting in front of the API.
  • Monitor API access and restrict clients using either suspicious devices or originating from risky IP addresses.
  • Identify non-human usage patterns such as impossibly quick transactions, and insert Captcha or other human detection controls.

7. Server Side Request Forgery

  • Server-Side Request Forgery (SSRF) can occur when an API fetches a remote resource without validating the user-supplied URL.
  • This enables an attacker to coerce the application to send a crafted request to an unexpected destination, even when protected by a firewall or a VPN.

Use case

An API accepts a URL as a parameter for a redirection, and an attacker finds that they can use this to redirect the response to a rogue site which is able to steal sensitive API data.

An attacker can force an API to load resources from a server under their control; this is the basis of a key injection attack in JWTs.

An API allows access to the local host allowing an attacker to use malform requests to access local resources.

How to prevent

  • Precisely define the schemas, types, and patterns you will accept in requests at design time and enforce them at runtime.
  • Prevent your API server from following HTTP redirections.
  • Use an allow list of permitted redirects or accesses.
  • Restrict the range of allowed URL schemes and ports allowed.
  • Use a standard implementation for the library responsible for loading resources making sure it cannot access the local host, and uses sanitized URLs from a safe URL parser.

8. Security misconfiguration

Poor configuration of the API servers allows attackers to exploit them.

Use case

Unpatched systems

Unprotected files and directories

Unhardened images

Missing, outdated, or misconfigured TLS

Exposed storage or server management panels

Missing CORS policy or security headers

Error messages with stack traces

Unnecessary features enabled

How to prevent

  • Automate the hardening and patching processes of the full API stack (code, libraries, containers)
  • Automate test to API endpoints for misconfiguration (TLS version, cyphers, bad verbs)
  • Disable unnecessary features.
  • Restrict administrative access.
  • Define and enforce all outputs, including errors.

9. Improper inventory management

Attackers find non-production versions of the API (for example, staging, testing, beta, or earlier versions) that are not as well protected as the production API, and use those to launch their attacks.

Use case

DevOps, the cloud, containers, and Kubernetes make having multiple deployments easy (for example, dev, test, branches, staging, and old versions).

Desire to maintain backward compatibility forces to leave old APIs running.

Old or non-production versions are not properly maintained, but these endpoints still have access to production data.

Once authenticated with one endpoint, attackers may switch to the other, production one.

How to prevent

  • Keep an up-to-date inventory of all API hosts.
  • Limit access to anything that should not be public.
  • Limit access to production data, and segregate access to production and non-production data.
  • Implement additional external controls, such as API firewalls.
  • Properly retire old versions of APIs or backport security fixes to them.
  • Implement strict authentication, redirects, CORS, and so forth.

10. Unsafe API Consumption

  • Modern API-based systems tend to be highly interconnected, frequently consuming upstream APIs.
  • Unfortunately, these upstream APIs may themselves be vulnerable and put their consumers at risk.

Use case

An upstream API may inadvertently store data provided to it by a consumer, thereby violating the data governance regulations of the consumer.

An upstream API provider may be attacked and compromised and then pass malicious data to its consumers due to insufficient internal controls. A typical example is an SQL injection attack.

How to prevent

  • Just like the case with user input, do not trust upstream API data.
  • Filter and sanitize any input data regardless of origin, particularly against injection attacks.
  • Ensure that upstream API providers specify their API contract, and use runtime mechanisms to enforce this contract.
  • Assume upstream API providers are part of your supply chain and verify their internal development processes.
  • Use a secure communication channel at all times.

This sums our discussion for Part 1 . In next article we will see how to create a strategic API security model and effective security checklists for keeping the APIs secure

--

--