OWASP API Top 10 — API Security

TL;DR — The blogs covers code samples that highlight common vulnerabilities related to the OWASP API Top 10. This blog will cover each category from the OWASP API Top 10 list with the help of vulnerable code sample. The goal is to understand the mistake, impact and the patch for the same.
This blog will provide a concise overview of the top security challenges developers and organizations face when designing, developing, and securing APIs.

Shout out to the great team behind OWASP API Top 10 project for helping raise awareness and providing guidance for addressing security issues specific to API architectures and implementations.
So let’s jump in to take a look at a vulnerable code sample from each of the OWASP API Top 10 category.
1. Broken Object-Level Authorization (BOLA)

Mistake: It lacks proper authorization checks, allowing any user to access the information of any other user without verifying if the requester has the necessary privileges.
Impact: Unauthorized users can retrieve sensitive user data, leading to potential data breaches and privacy violations.
Example Patch:

Implement proper authorization checks before returning user information. Verify the requester’s privileges or access rights to ensure only authorized users can access user data for a specific ID.
2. Broken Authentication

Mistake: The code snippet performs an insecure authentication check by comparing the provided username and password directly with hardcoded values.
Impact: The insecure authentication check leaves the system vulnerable to brute-force attacks, credential guessing, and unauthorized access to user accounts.
Example Patch:

To address this vulnerability, implement proper authentication mechanisms:
- Store passwords securely by hashing and salting them.
- Retrieve stored user credentials and compare them using secure comparison methods.
- Use established authentication frameworks or libraries.
- Implement stronger authentication measures such as session management or token-based authentication.
- Follow best practices for password storage and handling, using secure algorithms like bcrypt for password hashing.
3. Excessive Data Exposure aka Broken Object Property Level Authorization

Mistake: The mistake in the code is that it exposes sensitive data by returning all user records without considering the sensitivity of the information.
Impact: The impact of this vulnerability is that it allows unauthorized access to sensitive user data, potentially leading to data breaches, privacy violations, and misuse of personal information.
Example Patch:

req.user.isAdmin
). Only admin users are granted access to retrieve user data. Sensitive fields are filtered or excluded from the API response by creating a sanitized version of the user data that includes only non-sensitive fields.To address the vulnerability and prevent sensitive data exposure:
- Implement Proper Data Filtering:
- Only include necessary and non-sensitive fields in the API response.
- Exclude or mask sensitive fields, such as passwords or personally identifiable information (PII), from the response.
2. Apply Access Controls:
- Implement authorization mechanisms to restrict access to the
/api/users
endpoint. - Ensure that only authenticated and authorized users can access the user data.
3. Limit Result Set:
- Consider implementing pagination or result limits to avoid returning large amounts of data in a single response.
- Limit the number of user records returned per page or specify query parameters to control the result set.
4. Lack of Resources & Rate Limiting aka Unrestricted Resource Consumption

Mistake: The mistake in the code has the absence of rate limiting for the transfer
API endpoint, allowing potential abuse and unauthorized usage of the transfer functionality.
Impact: The impact of this vulnerability is that it exposes the transfer functionality to abuse, including potential denial-of-service attacks, unauthorized transfers, or excessive usage of system resources.
Example Patch:

@limiter.limit()
decorator sets the rate limit for the transfer
endpoint to 10 requests per minute as an example. Adjust the rate limit values according to your specific requirements.5. Broken Function Level Authorization aka BFLA

Mistake: The code snippet lacks adequate function-level authorization for the DeleteUser
API endpoint. It only checks if the requester has the "Admin" role but does not perform further validation or verification.
Impact: The vulnerability allows any user with the “Admin” role to delete user accounts without proper authorization, potentially leading to unauthorized deletion of user data and disruption of services.
Example Patch:

To address the inadequate function-level authorization:
- Validate Requester’s Authority:
- Verify if the authenticated user or requester has the necessary privileges or permissions to delete a user.
- Implement additional checks to ensure the requester is authorized to perform the deletion.
2. Perform Ownership Validation:
- Verify if the requester is the owner of the user being deleted or has the appropriate role/permission for such actions.
- Validate the requester’s identity or ownership before allowing the deletion.
6. Mass Assignment aka Unrestricted Access to Sensitive Business Flows

Mistake: The code snippet is vulnerable to mass assignment, where the entire newUser
object received in the request body is directly used for creating a new user without proper validation or selective assignment of properties.
Impact: The mass assignment vulnerability can lead to security risks such as overwriting sensitive properties, unintended data modifications, or unauthorized updates to user data.
Example patch:

username
, email
, etc.) from the newUser
object received in the request body. Other properties are excluded from the assignment, reducing the risk of unintended modifications or overwriting sensitive fields.To address the mass assignment vulnerability, implement the following measures:
- Validate and Sanitize Input:
- Only allow specific properties to be assigned during user creation.
- Validate and sanitize the input to ensure that only safe and expected properties are accepted.
2. Use Property Whitelisting:
- Define a whitelist of properties that can be assigned during user creation.
- Assign only the whitelisted properties from the
newUser
object to the newly created user.
3. Apply Object Mapping or DTOs:
- Utilize Object Mapping techniques or Data Transfer Objects (DTOs) to handle the assignment of properties from the request body to the user object.
- Map and assign only the necessary properties to the user object, excluding any sensitive or unintended fields.
7. Server Side Request Forgery

Mistake: The code blindly accepts and fetches data from any URL specified in the url
query parameter without proper validation or restriction.
Impact: This vulnerability can lead to SSRF attacks, where an attacker can abuse the functionality to make requests to internal or restricted resources within the server’s network. The attacker can potentially access sensitive data, bypass security controls, or perform actions on behalf of the server.
Example patch:

netloc
(domain) against a list of allowed domains. Only URLs from the ALLOWED_DOMAINS
list are permitted. If an invalid or unauthorized URL is detected, an exception is raised. Additionally, appropriate error handling is implemented to handle and respond to invalid URL requests.8. Security Misconfiguration

Mistake: The mistake in the code is the insecure Cross-Origin Resource Sharing (CORS) configuration, specifically allowing all origins ('*'
) and permitting multiple methods without proper consideration.
Impact: The insecure CORS configuration allows any origin to make requests to the API, potentially exposing sensitive data or functionalities to unauthorized sources. It increases the risk of Cross-Site Scripting (XSS), Cross-Site Request Forgery (CSRF), and other web application vulnerabilities.
Example patch:

origin
field is restricted to https://example.com
, allowing requests only from that specific origin. The methods
field is limited to GET
and POST
methods, while the allowedHeaders
field includes only the necessary 'Content-Type'
header.To address the insecure CORS configuration, follow these steps:
- Restrict Allowed Origins:
- Specify the allowed origins explicitly instead of using a wildcard (
'*'
). - Only allow specific trusted domains or origins that require access to the API.
2. Specify Allowed Methods and Headers:
- Limit the allowed methods and headers to those necessary for the API’s intended usage.
- Avoid including unnecessary or potentially dangerous methods and headers.
9. Improper Inventory Management aka Improper Assets Management

Mistake: The mistake in the code is improper inventory management, including lack of input validation, absence of authentication and authorization checks, no inventory constraints, and missing logging of inventory changes..
Impact: The vulnerability can lead to unauthorized or malicious modification of the inventory, unexpected behavior, data integrity issues, and difficulty in tracking inventory changes.
Example Patch:

item_name
and quantity
, enforces authentication and authorization checks, and implements constraints to handle potential issues related to inventory management. Additionally, the code logs inventory changes using a log_inventory_change()
function, allowing for better tracking and monitoring of inventory modifications.Input Validation: Validate and sanitize the item_name and quantity inputs to prevent injection attacks or unexpected data. Ensure that the item name and quantity adhere to the required format and data types.
Inventory Constraints: Implement constraints on the inventory, such as maximum quantities allowed for each item or validation for duplicate item entries. Handle cases where an item with the same name already exists in the inventory.
Secure Logging: Log inventory changes to monitor modifications and detect potential security issues or anomalies. Ensure that the logged information does not contain sensitive data. Enforce inventory constraints and handle duplicate item entries. Additionally, log inventory changes for monitoring and auditing purposes.
10. Unsafe Consumption of APIs

Mistakes:
- Lack of Input Validation: The code doesn’t validate or sanitize the
userId
parameter received from the request, making it vulnerable to injection attacks or unexpected input. - Absence of Authentication and Authorization: The code doesn’t include any authentication or authorization checks to ensure that the requester has the necessary permissions to access the API.
- Inadequate Error Handling: The code uses a generic error handler without proper handling of specific error scenarios, potentially exposing sensitive information or leaking implementation details.
Impact: The vulnerabilities in the code can lead to security risks, including unauthorized access to user data, injection attacks, and potential exposure of sensitive information or system vulnerabilities.
Example Patch:

userId
parameter using the isValidUserId()
function. If the ID is deemed valid, the code proceeds with authenticating and authorizing the requester before making the request to the external API. Additionally, it provides a specific error message for invalid user IDs.Check out my previous blog on API security for developers. This is an high level checklist for Developers that includes recommendation to securely develop APIs. This checklist focuses on strategies and solutions to understand and mitigate the unique vulnerabilities and security risks of Application Programming Interfaces (APIs).
What next? In the series of API security blogs I am planning to cover how to write detection rule using semgrep by understanding the patterns of vulnerable code.