Developer's Guide: Best Practices For Ensuring Robust API Security
Published: 2023-12-18 12:23:29

by [Oseni Shuaib](https://blog.openreplay.com/authors/oseni-shuaib)


<blockquote><em>
API security is implementing protective measures to safeguard APIs and the data they transmit, ultimately preventing unauthorized access and ensuring the reliability of software systems and services. It is critical for protecting your data and applications against unauthorized access, data modification, or destruction. This article explores best practices on how developers can safeguard their APIs
</em></blockquote>


<div style="background-color:#efefef; border-radius:8px; padding:10px; display:block;">
<hr/>
<h3><em>Session Replay for Developers</em></h3> 
<p><em>Uncover frustrations, understand bugs and fix slowdowns like never before with <strong><a href="https://github.com/openreplay/openreplay" target="_blank">OpenReplay</a></strong> — an open-source session replay suite for developers. It can be <strong>self-hosted</strong> in minutes, giving you complete control over your customer data.</em></p>
<img alt="OpenReplay" style="margin-top:5px; margin-bottom:5px;" width="768" height="400" src="https://raw.githubusercontent.com/openreplay/openreplay/main/static/openreplay-git-hero.svg" class="astro-UXNKDZ4E" loading="lazy" decoding="async">
<p><em>Happy debugging! <a href="https://openreplay.com" target="_blank">Try using OpenReplay today.</a></em><p>
<hr/>
</div>



With the increasing reliance on Application Programming Interface (APIs) in modern software development, APIs have become prime targets for cyberattacks. In a survey conducted by [Palo Alto](https://www.paloaltonetworks.com/resources/research/api-security-statistics-report) in 2023, 92% of the organizations participating in the study had encountered at least one API-related security incident within the past year. Among these organizations, 57% faced multiple API-related security incidents. Let's discuss the risks and how to avoid them.

## OWASP API Security Risk 

The [Open Web Application Security Project](https://owasp.org/) (OWASP) is a non-profit organization dedicated to improving software security. It provides resources, including guidelines, tools, and best practices, to help developers and organizations enhance application security. The organization aims to raise awareness about application security issues and offer practical solutions to mitigate risks.

In 2019, the organization added the Security [API Top 10 list](https://owasp.org/API-Security/editions/2019/en/0x11-t10/) to their annual reports. This list identifies the top 10 API security risks and guides developers, offering a comprehensive understanding of the prevalent threats in the API ecosystem. OWASP maintains the Top 10 API risks, with the latest version [published in 2023.](https://owasp.org/API-Security/editions/2023/en/0x11-t10/)

| **OWASP API Top 10 2019 list**         | **OWASP API Top 10 2023 list**                     |
| -------------------------------------- | -------------------------------------------------- |
| 1. Broken Object Level Authorization   | 1. Broken Object-Level Authorization               |
| 2. Broken User Authentication          | 2. Broken Authentication                           |
| 3. Excessive Data Exposure             | 3. Broken Object Property Level Authorization      |
| 4. Lack of Resources & Rate Limiting   | 4. Unrestricted Resource Consumption               |
| 5. Broken Function Level Authorization | 5. Broken Function Level Authorization             |
| 6. Mass Assignment                     | 6. Unrestricted Access to Sensitive Business Flows |
| 7. Security Misconfiguration           | 7. Server-Side Request Forgery                     |
| 8. Injection                           | 8. Security Misconfiguration                       |
| 9. Improper Assets Management          | 9. Improper Inventory Management                   |
| 10. Insufficient Logging & Monitoring  | 10. Unsafe Consumption of APIs                     |

## Understanding Each Risk
### Broken Object-Level Authorization

An API uses object-level authorization to ensure only authorized users can access the data it delivers. Broken object-level authorization (BOLA) occurs when an API fails to adequately enforce access controls at the object level, allowing unauthorized users to view, modify, or delete data they shouldn’t have access to. This risk indicates that the API doesn’t correctly check who can perform what actions on specific objects, potentially exposing sensitive data.


> Example: Purple-Cart is an online shopping platform where users can view and edit their order details. In this case, a broken object-level authorization would allow one user to manipulate or even delete another user's order information.

The impact of this risk can be severe. It can result in data breaches, privacy violations, and financial losses. Unauthorized access to sensitive data can harm an organization's reputation and lead to legal consequences, making it a risk that demands careful mitigation.


### Broken Authentication

Broken Authentication is a vulnerability that allows unauthorized access to an application or API due to flaws in the authentication process. This occurs when credentials are not properly protected, sessions are not adequately managed, or weak authentication methods are in place.


> Example: An API that does not require users to confirm their identity by providing their current password when changing their email address can be exploited by attackers to take over user accounts.

The impact of broken authentication can be detrimental, leading to unauthorized account access, identity theft, and misuse of sensitive data.


### Broken Object Property Level Authorization (BOLA)

In this case, the attack involves gaining unauthorized access to sensitive information by either [Excessive Data Exposure](https://owasp.org/API-Security/editions/2019/en/0xa3-excessive-data-exposure/) (Exposing sensitive or unnecessary data to users) or [Mass Assignment](https://owasp.org/API-Security/editions/2019/en/0xa6-mass-assignment/) (Assigning values to multiple attributes of an object at once). By exploiting this vulnerability, a user without validated access permissions can read and/or modify object values of the endpoint.


> Example: An online banking application with an API endpoint that allows users to retrieve their account information. The endpoint takes the user's account number as a parameter and returns an object containing the user's account balance, transaction history, and other account details.

Exploiting this vulnerability could result in an attacker gaining access to potentially sensitive data, including personal identifiable information (PII). In addition, an attacker exploiting this type of vulnerability could change objects' properties to escalate privileges, manipulate data, and bypass security mechanisms.


### Unrestricted Resource Consumption

This is a type of [denial-of-service (DoS)](https://www.cloudflare.com/learning/ddos/glossary/denial-of-service/) attack that aims to exhaust the resources of a target system or application. Unrestricted resource consumption occurs when an attacker can consume excessive resources from an API, such as CPU, memory, or bandwidth. This can be done by making many requests to the API.


> Example: A social media application has an API endpoint that allows users to reset their forgotten passwords. The endpoint takes the user's email address as a parameter and sends an email with a reset password link.
However, the endpoint does not implement rate limiting or other measures to prevent unrestricted resource consumption. This means that an attacker could send a large number of requests to the endpoint to reset the passwords of a large number of users.

Exploiting this vulnerability in an application causes performance degradation, outages, and even financial losses.


### Broken Function Level Authorization

Broken Function Level Authorization occurs when an API allows unauthorized users to access certain functions or perform actions they should not be able to access. This vulnerability often arises from improper access control measures.


> Example:  Consider an e-commerce application where regular users can modify product prices thanks to a broken function level authorization. This could lead to financial losses, confusion, and potential system misuse.

The impact of broken function level authorization can be significant, resulting in financial losses, user dissatisfaction, and misuse of system functionality. 


### Unrestricted Access to Sensitive Business Flows

This involves exploiting the business model of an application to obtain unrestricted access to sensitive business flows. To exploit this vulnerability, an attacker tries to understand the business logic behind the target API, find sensitive business flows, and automate access to them.


> Example: A user preventing other users from using a cinema application by reserving all movie premiere slots.

Unrestricted access to sensitive business flows can allow attackers to steal data, launch DoS attacks, and commit fraud, damaging the company's finances and reputation.


### Server Side Request Forgery (SSRF)

SSRF occurs when an attacker can force an API server to make unauthorized requests to other systems. 


> Example: A Social media application with an API endpoint allowing users to share links. The endpoint takes the URL of the link as a parameter and returns a preview of the link. Attackers can send a malicious URL and initiate port scanning on the internal network using the API's endpoint to uncover open ports.

With SSRF, attackers can gain access to unauthorized networks, tamper data, or even fully compromise a server. 


### Security Misconfiguration

Security Misconfiguration happens when an API or its components are not securely configured. This might include default settings, overly permissive permissions, or exposed sensitive information that should remain confidential.


> Example: Consider a cloud-based API service with publicly accessible storage buckets that contain sensitive customer data by default. A security misconfiguration might make these buckets accessible to anyone online, leading to data leaks.

The impact of security misconfiguration is substantial, as it can result in data breaches or unauthorized access.


### Improper Inventory Management

This occurs when an organization does not have a complete and accurate inventory of its APIs or when it does not have a process for managing and retiring old APIs. If an organization does not have a process for managing old or deprecated endpoints, these endpoints may still be accessible to attackers. This can allow attackers to exploit these endpoints to gain unauthorized access to sensitive data or functionality.

Improper Inventory Management can also occur when an organization does not have a process for managing API keys; these keys may be exposed to the public. This can allow attackers to steal these keys and use them to gain unauthorized access to APIs.


### Unsafe Consumptions of APIs

This occurs when an API implementation or back-end system that integrates with an external API does not validate and sanitize its inputs or verify the endpoint. 

Additionally, failure to verify the authenticity of an API server could allow an attacker to impersonate a legitimate API server and send malicious requests to the client.


> Example: A web application uses an API to authenticate users. The web application does not validate the user input sent to the API. An attacker submits malicious input to the web application, which is then passed to the API. The API does not validate the input, so the malicious input is executed on the API server.
The malicious input gives the attacker control over the API server. The attacker then uses the API server to steal sensitive data from the web application's users.
    

This vulnerability, when exploited, can result in data theft and exposure to various injection attacks.


<CTA_Middle_Security />



## Mitigation Strategies

Mitigation strategies are essential for safeguarding your APIs against common security risks. By taking proactive measures, you can significantly reduce the likelihood of vulnerabilities being exploited. Here are practical strategies for addressing the most prevalent API security risks:

### Preventing Broken Object Level Authorization
To prevent this vulnerability, it's essential to implement strict access controls and authentication measures. To mitigate BOLA:

- **Token Based Authentication**: This helps mitigate broken object-level authorization by leveraging digitally-signed tokens, issued upon successful user login, to validate and control access to specific objects, ensuring secure and authorized interactions within the system.
- **User Access Control List(ACL)**: This vulnerability can be mitigated by explicitly defining and regulating user or group access rights to specific resources, ensuring precise and authorized interactions while preventing unauthorized access. 
- **Performing Tests**: Regularly audit and test your authorization mechanisms to identify and rectify vulnerabilities.

Tools that can be used to test for BOLA vulnerabilities are:

- [JWT_Tool](https://github.com/ticarpi/jwt_tool) 
- [Burp Suite](https://portswigger.net/burp/communitydownload)

### Protecting Against Excessive Data Exposure
To protect against excessive data exposure: 

- Implement proper data filtering and access controls. 
- Only provide the data necessary for each user's role or request. 
- Ensure that sensitive data is not inadvertently exposed, and regularly review your data access policies.

### Enhancing Authentication Security
Enhancing authentication security involves:

- **Multifactor Authentication**: This significantly enhances authentication security by requiring users to provide multiple forms of identification, such as passwords and time-sensitive codes, adding an extra layer of protection against unauthorized access even if passwords are compromised.
- **Limiting Login Attempts**: By enforcing limits on login attempts, you mitigate the risk of unauthorized entry, making it more challenging for attackers to guess or crack passwords through repetitive and automated login attempts.
- **Session Management**: This ensures that user sessions are appropriately authenticated and authorized, minimizing the risk of unauthorized access by implementing secure session management practices, such as unique session identifiers and session timeouts, thereby preventing session hijacking and unauthorized session reuse.

Tools
- [OWASP ZAP](https://www.zaproxy.org/)
- [JHijack](https://sourceforge.net/projects/jhijack/)


### Guarding Against Injection Attacks 

Input validation is a critical defense against injection attacks, such as SQL injection and cross-site scripting (XSS). Validating and sanitizing user inputs prevent malicious code or unexpected characters from being executed. Proper input validation ensures that user-supplied data is within acceptable parameters, eliminating attempts to manipulate queries or inject malicious scripts.

References

- [Unicode Identifier and Pattern Syntax](https://unicode.org/reports/tr31/)
- [Unicode Script Property](https://unicode.org/reports/tr24/)

### Guarding Against SSRF Attacks

- **Firewalls**: Firewalls are crucial in mitigating Server-Side Request Forgery (SSRF) attacks by acting as a protective barrier between the internal network and external entities. They can be configured to inspect and filter incoming and outgoing traffic, helping to prevent malicious requests associated with SSRF.
- **Whitelisting**: Implementing whitelists is a powerful strategy to fortify defenses against Server-Side Request Forgery (SSRF) attacks. Use whitelists to define approved URLs and IP addresses the application can access. This reduces the attack surface and blocks unauthorized SSRF attempts.

### Ensuring Proper Security Configuration
Ensuring proper security configuration entails following best practices for secure server and application configurations. Here are some ways to ensure best practices:
- **Updates and Patches**: Updating and patching are crucial for mitigating security risks associated with known vulnerabilities. Regular updates help close these security gaps, reducing the likelihood of unauthorized access, data breaches, and other threats.
- **Removing Default Accounts**: If not removed, default accounts can serve as potential entry points for attackers. Threat actors commonly exploit default credentials, often publicly known, to gain unauthorized access. Removing default accounts mitigates this risk by eliminating predictable points of entry.


Reference

- [OWASP Testing Guide: Configuration Management](https://owasp.org/www-project-web-security-testing-guide/latest/4-Web_Application_Security_Testing/02-Configuration_and_Deployment_Management_Testing/README)
- [CIS Security Configuration Guides/Benchmarks](https://www.cisecurity.org/cis-benchmarks/)
- [NIST Guide to General Server Hardening](https://csrc.nist.gov/publications/detail/sp/800-123/final)

## Case Studies

### Azure API Management SSRF Vulnerability
Research by [Ocra Security](https://orca.security/resources/blog/ssrf-vulnerabilities-azure-api-management/) found it was possible to gain access to the internal network resources of one of Microsoft’s products (Azure), which could potentially compromise the security of this cloud service. This vulnerability was reported on November 12th, 2022.

The researchers discovered that the vulnerability could have allowed attackers to obtain information about Azure Wire Endpoints (an internal static IP address Azure Services use to communicate through the [WAAgent](https://learn.microsoft.com/en-us/azure/virtual-machines/extensions/agent-linux)), such as installed extensions, certificates, and their corresponding private keys.

The APIM engineering team completed deploying a fix to sufficiently block access to local ports/resources on the VM on November 16th, 2022.

### Parler API Attack
Parler, a social media platform, had its API exposed to the public, allowing attackers to access and download vast amounts of user data, posts, and media files. The incident revealed significant flaws in Parler's API security, particularly in the authentication process (Broken Authentication) and data access controls. Read more about the attack [here](https://salt.security/blog/unpacking-the-parler-data-breach). 

## Conclusion

The case studies of the SSRF vulnerability in Azure API Management and the Parler API attack emphasize the critical importance of API security. Key takeaways from these incidents include:

- The need for thorough security assessment.
- Rigorous input validation in API development.
- The significance of monitoring and identifying unusual or unauthorized API requests.

Developers must constantly educate themselves on potential vulnerabilities while investing in robust access controls, data filtering, and secure configuration practices. API security is not a one-time effort; it requires an ongoing commitment to safeguarding applications and user data.

## Resources
- [Important Steps to API Security](https://medium.com/@alpbeyazgul/25-important-steps-to-api-security-for-developers-9c23b21abb44) 
- [Checklist for Developers for Securing APIs](https://infosecwriteups.com/api-security-for-developers-58f971bcc2c1)
- [API Security Initiatives](https://www.csoonline.com/article/652754/6-notable-api-security-initiatives-launched-in-2023.html)