API Security - Checklist

·11 min read
API Security - Checklist

Covered basic security measures to consider while working on backend API's.

With API attackers increasingly targeting the business logic in APIs and undertaking malicious activities that can go on for weeks and even months, being aware of the main threats faced by today’s complex API ecosystems.

The OWASP API Security Top 10 provides the most up-to-date list of existing API security threats and highlights the need for dedicated API protections that go beyond traditional cybersecurity approaches.

WHO'S THIS FOR

  • Anyone who build or test API's.

1. Broken Object Level Authorization (BOLA)

BOLA refers to a failed access control process, allowing a user to get access to objects which they should not be authorized to access. This could lead to an unauthorized user accessing sensitive data, manipulating data, or executing functions.

Risk Rating 6.0

Let's create a scenario for a recipe app where users can view and manage their recipes. In this example, we'll illustrate both a positive scenario where a user retrieves their own recipe and a negative scenario where an attacker exploits a Broken Object Level Authorization (BOLA) vulnerability to access someone else's recipe.

Example — User Recipe Retrieval (GET Request):

Request:

GET /api/recipes/123 HTTP/1.1
Host: recipe-app.example.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/118.0
Accept: application/json
Authorization: Bearer valid_token_user123

In this positive scenario, a legitimate user (with ID 123) sends a GET request to retrieve their own recipe using their valid token (valid_token_user123). The server, in a secure implementation, verifies that the token corresponds to the user ID specified in the URL (123), allowing the user to access their own recipe.

** Negative Example — Exploiting BOLA (Recipe Retrieval):**

Request:

GET /api/recipes/456 HTTP/1.1
Host: recipe-app.example.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/118.0
Accept: application/json
Authorization: Bearer valid_token_user123   # Exploiting BOLA by using a valid token for user123

In this negative scenario, an attacker attempts to exploit a Broken Object Level Authorization (BOLA) vulnerability by sending a GET request to retrieve the recipe of a different user (recipe with ID 456) using their own valid token for user123. A BOLA vulnerability would mean that the server fails to properly check the association between the token and the recipe ID specified in the URL, allowing unauthorized access to recipes.

Prevention

  • Implement an authorization mechanism that checks whether the logged-in user has permission to perform the action.
  • Use this authorization mechanism in all functions that access sensitive data.
  • Use randomly generated GUIDs (as they are hard to guess) as object identifiers for user requests.

2. Broken Authentication

Attackers can easily target authentication processes, especially if they are fully exposed or accessible to the public. The second most frequent vulnerability reported by OWASP is broken user authentication, which enables attackers to utilize credential stuffing, stolen authentication tokens, and brute-force attacks to obtain unauthorized access to apps.

Your most sensitive endpoints are authentication and password reset endpoints.

Risk Rating 8.0

Example: Credential Stuffing:

Scenario: An attacker attempts to gain unauthorized access by using a list of known username and password pairs obtained from a previous data breach.

POST /api/authenticate HTTP/1.1
Host: api.example.com
Content-Type: application/json
Accept: application/json
 
{
    "username": "legitimate_user",
    "password": "weak_password"   # Using a password obtained from a data breach
}

Example: Sensitive Operations Without Password Confirmation:

Scenario: An API allows users to change their email address without asking for password confirmation.

PUT /api/user/settings HTTP/1.1
Host: api.example.com
Authorization: Bearer valid_user_token
Content-Type: application/json
Accept: application/json
 
{
    "new_email": "new.email@example.com"
}

Example: Weak Passwords:

Scenario: A user sets a weak password during the registration process.

POST /api/register HTTP/1.1
Host: api.example.com
Content-Type: application/json
Accept: application/json
 
{
    "username": "new_user",
    "password": "123456"   # Weak password
}

Prevention

  • Make sure you know all the possible flows to authenticate to the API (mobile/ web/deep links that implement one-click authentication/etc.)
  • Credential recovery/forgot password endpoints should be treated as login endpoints in terms of brute force, rate limiting, and lockout protections.
  • Require re-authentication for sensitive operations (e.g. changing the account owner email address/2FA phone number).

3. Broken Object Property Level Authorization

When allowing a user to access an object using an API endpoint, it is important to validate that the user has access to the specific object properties they are trying to access.

Risk Rating 5.3

In this example, we'll consider an API for managing user profiles, where users can view and update their own profiles.

Example: Exposing Sensitive Properties

The API endpoint inadvertently exposes sensitive properties, such as the user's role, which should not be visible to the user.

GET /api/profiles/user123 HTTP/1.1
Host: api.example.com
Authorization: Bearer valid_token_user123

And the response includes sensitive information:

{
    "userId": "user123",
    "username": "john_doe",
    "email": "john.doe@example.com",   
    "role": "user" # Sensitive property exposed
}

In this case, the API exposes the user's role property even though the user shouldn't have access to it.

Example: Unauthorized Modification

The API endpoint allows a user to update their profile, including modifying sensitive properties like their role, which the user should not be able to change.

PUT /api/profiles/user123 HTTP/1.1
Host: api.example.com
Authorization: Bearer valid_token_user123
Content-Type: application/json
 
{
    "userId": "user123",
    "username": "john_doe",
    "email": "updated_email@example.com",
    "role": "admin"   # Unauthorized modification of sensitive property
}

The API updates the profile, including modifying the role to "admin," which the user should not have the privilege to change.

Prevention

  • Ensure that sensitive properties are not exposed to users who shouldn't have access.
  • Implement proper authentication and authorization checks before allowing users to modify object properties.
  • Follow the principle of least privilege, granting users only the necessary permissions to perform their intended actions.
  • Validate API responses from a central schema that filters out object properties that should not be visible to the requesting user.

4. Unrestricted Resource Consumption

API requests consume back-end resources such as network, CPU, memory, and storage. APIs don’t always impose restrictions on the size or number of resources that can be requested by the client or user. Lack of rate and resource limiting doesn’t just potentially impact performance of back-end compute though. Lack of limiting also opens the door to many types of attacks including Denial of Service (DoS), brute-forcing, enumeration, and credential stuffing.

Lack of resource limit:

Attackers exploit lack of resource limiting by crafting a single API call that can overwhelm an application, impacting the application’s performance and responsiveness or causing it to become unresponsive.

Lack of rate limit

Attackers exploit the lack of rate limiting by crafting and submitting high volumes of API requests to overwhelm system resources, brute force login credentials,

No restrictions on third party services

A cloud-based file storage service allows users to upload and store files, share them with others, and access them from anywhere. The service does not have any restrictions on the number of files a user can upload simultaneously or the size of each file.

Risk Rating 8.0

Example: Email Bombing Attack

In this scenario, the API lacks proper resource limits, allowing an attacker to perform an email bombing attack by sending a large number of requests to overwhelm the system.

POST /api/send-email HTTP/1.1
Host: api.example.com
Authorization: Bearer valid_token_attacker
Content-Type: application/json
 
{
    "to": "victim@example.com",
    "subject": "Important Message",
    "body": "This is an email bombing attack."
}

The attacker sends multiple requests with different email content or recipients to exhaust the API's resources:

POST /api/send-email HTTP/1.1
Host: api.example.com
Authorization: Bearer valid_token_attacker
Content-Type: application/json
 
{
    "to": "victim@example.com",
    "subject": "Another Attack",
    "body": "This is another email bombing attack."
}

Without proper limits, the API processes an excessive number of email requests, consuming resources such as CPU, memory, and network bandwidth.

Prevention

  • Implement execution timeouts for API requests to limit the duration of each operation.
  • Set a maximum allocable memory limit to prevent memory exhaustion attacks.
  • Limit the number of file descriptors, processes, and upload file size to prevent abuse.
  • Control the number of records per page returned in a single request-response to prevent data flooding.
  • Implement spending limits or rate limiting for third-party service integrations to control costs.
  • Limit/throttle how many times or how often a single API client/user can execute a single operation (e.g., validate an OTP, or request password recovery without visiting the one-time URL).

5. Broken Function Level Authorization (BFLA)

Exploitation requires the attacker send legitimate API calls to an endpoint to which they should not have access; for instance, replacing the HTTP method from GET to PUT, or changing the "users" string in the URL to "admins."

Risk Rating 8.0

Scenario: Insecure API Endpoint Manipulation on an Online Learning Platform

  1. Instructor Dashboard API Endpoint:

    • Instructor Dashboard API Endpoint: /api/instructor/dashboard
    • Student Dashboard API Endpoint: /api/student/dashboard
    • Both endpoints provide different functionalities based on the user role.
  2. Legitimate Student Access:

    A legitimate student sends a request to access their own dashboard:

    GET /api/student/dashboard HTTP/1.1
    Host: learning-platform.example.com
    Authorization: Bearer valid_token_student

    The response includes the student's dashboard content.

  3. API Endpoint Manipulation to Access Instructor Dashboard:

    The student attempts to manipulate the API endpoint to access the instructor's dashboard:

    GET /api/instructor/dashboard HTTP/1.1
    Host: learning-platform.example.com
    Authorization: Bearer valid_token_student

    Surprisingly, the response includes the instructor's dashboard content, allowing the student to modify course content, grade assignments, and perform other instructor-specific actions.

Prevention

  • Implement proper authentication and authorization checks for each API endpoint.
  • Enforce access controls based on the user's role and permissions within the API.
  • Utilize role-based access control (RBAC) to differentiate between student and instructor roles.
  • Implement secure token management to ensure that users can only access functionalities based on their authorized roles.

6. Unrestricted Access to Sensitive Business Flows

Sensitive business flows are exposed without risk evaluation of how the functionality could harm the business if used in an automated and excessive manner. Common examples of sensitive business flows and risk of excessive access associated with them include:

  • An attacker can buy all the stock of a high-demand item at once and resell for a higher price.
  • A bad actor can create a comment/post flow, spamming a company’s system.
  • An attacker can reserve all the available slots for a given service and prevent other users from using the system.

This type of attack is notoriously hard to detect and protect against. Attacks in this category derive from a series of requests, in which each individual request is entirely legitimate.

Risk Rating 5.3

Example: Bulk Booking and Cancellation Attack

The attacker exploits the Unrestricted Access to Sensitive Business Flows vulnerability by booking a significant portion of the available seats without incurring cancellation fees:

# Attacker books multiple seats
POST /api/bookings HTTP/1.1
Host: airline-example.com
Content-Type: application/json
Authorization: Bearer valid_attacker_token
 
{
    "flightId": "ABC123",
    "seatNumber": "A2"
}
 
# ... (repeat for additional seats)

After successfully booking a substantial number of seats, the attacker decides to cancel all the reservations simultaneously just 1 day before flight, taking advantage of the absence of cancellation fees:

# Attacker cancels all booked seats
DELETE /api/bookings?flightId=ABC123 HTTP/1.1
Host: airline-example.com
Authorization: Bearer valid_attacker_token

The attacker, aware of the situation, takes advantage of the discounted prices and purchases a seat at a much cheaper rate. This results in financial damage to the airline as it has to sell some seats at a significantly reduced price, impacting revenue for the affected flight.

Prevention

  • Introduce cancellation fees to deter attackers from abusing the cancellation process.
  • Business – identify the business flows that might harm the business if they are excessively used. Then Implement rate limiting or restrictions on the number of simultaneous (Example:bookings or cancellations) from a single user.
  • Secure and limit access to APIs that are consumed directly by machines, such as developer and B2B APIs.

7. Server Side Request Forgery (SSRF)

Server-Side Request Forgery (SSRF) flaws occur when an API is fetching a remote resource without validating the user-supplied URL. The attacker gains information about the internal network structure, services, or data by exploiting the SSRF vulnerability. This information could be used for planning further attacks or gaining unauthorized access to internal resources.

Example: malicious S3 bucket URL

The attacker identifies the SSRF vulnerability and attempts to exploit it by providing a malicious S3 bucket URL:

POST /api/fetch-s3-data HTTP/1.1
Host: api.example.com
Content-Type: application/json
 
{
    "s3url": "https://s3.amazonaws.com/attacker-controlled-bucket/malicious-data.txt"
}

The API, lacking proper validation, fetches the provided S3 bucket URL, thinking it's legitimate, and retrieves data from the attacker-controlled bucket.

Prevention

  • Implement input validation on user-supplied URLs to block requests to internal or private resources.
  • Use a whitelist of allowed domains for external data retrieval.
  • Avoid using user-provided input directly in requests to fetch resources.
  • If possible, restrict the fetch capabilities to predefined and safe domains.

8. Security Misconfiguration

This occurs when an API is not securely configured, potentially exposing sensitive information or granting unnecessary permissions. Examples include logging error messages revealing server details, unnecessary HTTP methods enabled, or default credentials left unchanged.

An attacker, notices that detailed error messages are displayed when certain errors occur. The attacker intentionally triggers an error, such as by providing invalid input or causing a server-side issue.

Risk Rating 9.0

Example: Detail Error message

GET /api/sensitive-endpoint HTTP/1.1
Host: vulnerable-app.com

The server responds with a detailed error message that includes a stack trace:

Internal Server Error
Stack Trace:
...
File "/path/to/application/controllers/sensitive_controller.js", line 42, in sensitive_endpoint
    result = process_sensitive_data(request)
...

Prevention

  • Configure the web application to disable detailed error messages in production environments. Impletement Error Masking - using the response-rewrite plugin or custom data mask plugin.
  • Implement proper access controls and authentication mechanisms.
  • Need to configure the correct CORS settings in your apps.
  • Default Security Headers - APISIX enforces secure defaults with essential security headers, like Content Security Policy (CSP) and HTTP Strict Transport Security (HSTS), which are set. This reduces the risk of certain web-based attacks.

9. Improper Inventory Management

Maintaining a complete, accurate API inventory is critical to understanding potential exposure and risk. An outdated or incomplete inventory results in unknown gaps in the API attack surface and makes identifying older versions of APIs that should be decommissioned more difficult.

Unknown APIs, referred to as shadow APIs, and forgotten APIs, referred to as zombie APIs, typically aren’t monitored or protected by security tools.

Risk Rating 5.3

Example: Rate-Limiting Bypass in E-commerce API

Situation:

An e-commerce platform has a security feature to prevent someone from repeatedly trying to guess a user's password. Problem:

A developer discovers a test version of the e-commerce API that forgot to include the rate-limiting security feature.

POST /api/commerce/password HTTP/1.1
Host: test.api.commerce.org
Content-Type: application/json
 
{
    "userId": "123",
    "newPassword": "password123",
    "resetToken": "000000"  // Brute-forced token
}
 

** What Happens:**

The attacker can use automated tools to keep trying different passwords until they find the correct one, without any restrictions.

Prevention

  • Make API documentation available only to those authorized to use the API.
  • Know which of APIs poses most of the risk.
  • When newer versions of APIs include security improvements, perform a risk analysis to decide on the mitigation actions required for the older version.
  • Avoid using production data with non-production API deployments. If this is unavoidable, these endpoints should get the same security treatment as the production ones.

10. Unsafe Consumption of APIs

Developers tend to trust data received from 3rd party APIs, especially for APIs from wellknown companies. Thus, it sometimes has a lack of input validation and sanitization for those APIs.

  • Does not properly validate and sanitize the data from 3rd party companies.
  • Blindly follows redirections.
  • No timeout mechanism with 3rd party APIs.
  • No limit the number of resources.
  1. Exploiting Lack of Input Validation:

    • An attacker sends manipulated data to the weather API, injecting malicious content.

      GET /weather?location=<script>alert('XSS')</script> HTTP/1.1
      Host: weather-api.example.com
    • The website, lacking input validation, displays the injected script to users, potentially leading to a cross-site scripting (XSS) attack.

  2. Manipulating Redirections:

    • The attacker exploits the website's blind following of redirections to redirect API requests to a malicious server.

      GET /weather?location=malicious-server.example.com HTTP/1.1
      Host: weather-api.example.com
    • The website, blindly following redirections, unknowingly sends sensitive user location data to a malicious server.

  3. No Timeout Handling:

    • An attacker floods the website with a large number of requests to the weather API, causing a denial-of-service by consuming all available resources without a timeout mechanism.

      GET /weather?location=fake-location HTTP/1.1
      Host: weather-api.example.com
    • The website becomes unresponsive as resources are tied up in prolonged API requests.

  4. No Resource Limit:

    • An attacker repeatedly queries the weather API, exhausting the website's resources.

      GET /weather?location=fake-location HTTP/1.1
      Host: weather-api.example.com
    • The website's server becomes overloaded, impacting its performance and potentially causing a service outage.

Prevention

  • Implement strict input validation and sanitize data received from third-party APIs.
  • Securely handle API redirections, ensuring they are legitimate.
  • Set timeout mechanisms for API requests to prevent prolonged delays.
  • Enforce limits on the number of resources consumed from third-party APIs to prevent abuse and denial-of-service attacks.