## API Security ### General Tips - **Use HTTPS for API Communications** - Encrypts data transmitted between the client and server. - Helps to prevent eavesdropping, man-in-the-middle attacks, and other security threats. - Protects API keys, session tokens, and user data. - **Use OAuth2** - Instead of sharing credentials directly, it allows users to grant third-party applications limited access to the resources. - No credentials are ever shared with the API, just temporary access tokens. No need to store user passwords and can security integrate with third-party services. - **Use WebAuthn** - Newer standard that provides a more secure and user friendly way of authenticating users. - Uses public key cryptography and biometric factors (like fingerprints or facial recognition) - Makes it harder for attackers to compromise accounts using methods like phishing or credential stuffing - **Use leveled API keys** - Using a single API key for all services and operations can be risky. - Implement API keys that have varying access levels. Each key should have specific access permissions and scopes defined. (e.g. read-only, write, admin) - If an API key is compromised, it allows only limited access provided by the key, minimizing the blast radius. - Good idea to rotate keys regularly and have an easy mechanism for revoking keys immediately. If the function is made available, utilize expiration times. - **Implement Authorization** - Use Role-Based Access Control (RBAC) to ensure that clients can only access and modify the data that they are authorized for. - APIs should also follow the principle of least privilege. - **Rate Limiting** - Protects our APIs from becoming overwhelmed by malicious actors or buggy clients. - Can be based on IP address, user ID, API key, etc. - Can implement different limits for different types of requests (e.g. 1000 read req/sec and 500 write req/sec) - Improves security and improves performance and availability of your API - **API Versioning** - Allows you to evolve the API over time while maintaining backward compatibility. - Typically done by including the version number in the API endpoint URL like `GET /v1/users/123` - Allows the client to determine which version to use and allows for separation of documentation and requirements. - **Allow-Listing** - Allow access only to a predefined set of trusted entities like IP addresses, user IDs, or API keys. Everything else is denied-by-default. - **Use API Gateway** - Acts as a single entry point for clients to access back-end services and APIs - Provides a centralized for enforcing security policies, rate limiting, and authentication - Abstracts away the complexity of managing security features across individual services or APIs - Additional benefits include traffic management, caching, logging, and monitoring. - **Error Handling** - When errors occur, provide clients with descriptive error messages. - `Internal Server Error` vs `Failed to retrieve user data. Please check that you are authenticated and have sufficient permissions`. - Instead of exposing the use of SQL from an error message such as `SQL query failed due to malformed input containing a DROP TABLE command`, provide an error message like `Invalid input provided. Please review and try again`. - Never ever return full stack traces or expose internal error messages. The goal is to help legitimate clients while protecting sensitive information and attack vectors. - **Input Validation** - Validate request parameters, headers, payloads, and any other user-supplied input. - Failing to do so can lead to vulnerabilities like SQL injection, Cross-site Scripting, and other injection attacks. - Validation should be done on both the client side and the server side. Client side validation alone is not sufficient. ### OWASP Top 10 API Security Risks | Title | Description | | --------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | **API1: Broken Object Level Authorization** | APIs tend to expose endpoints that handle object identifiers, creating a wide attack surface of Object Level Access Control issues. Object level authorization checks should be considered in every function that accesses a data source using an ID from the user. | | **API2: Broken Authentication** | Authentication mechanisms are often implemented incorrectly, allowing attackers to compromise authentication tokens or to exploit implementation flaws to assume other user's identities temporarily or permanently. Compromising a system's ability to identify the client/user, compromises API security overall. | | **API3: Broke Object Property Level Authorization** | This category combines [API3:2019 Excessive Data Exposure](https://owasp.org/API-Security/editions/2019/en/0xa3-excessive-data-exposure/) and [API6:2019 - Mass Assignment](https://owasp.org/API-Security/editions/2019/en/0xa6-mass-assignment/), focusing on the root cause: the lack of or improper authorization validation at the object property level. This leads to information exposure or manipulation by unauthorized parties. | | **API4: Unrestricted Resource Consumption** | Satisfying API requests requires resources such as network bandwidth, CPU, memory, and storage. Other resources such as emails/SMS/phone calls or biometrics validation are made available by service providers via API integrations, and paid for per request. Successful attacks can lead to Denial of Service or an increase of operational costs. | | **API5: Broken Function Level Authorization** | Complex access control policies with different hierarchies, groups, and roles, and an unclear separation between administrative and regular functions, tend to lead to authorization flaws. By exploiting these issues, attackers can gain access to other users’ resources and/or administrative functions. | | **API6: Unrestricted Access to Sensitive Business Flows** | APIs vulnerable to this risk expose a business flow - such as buying a ticket, or posting a comment - without compensating for how the functionality could harm the business if used excessively in an automated manner. This doesn't necessarily come from implementation bugs. | | **API7: Server Side Request Forgery** | Server-Side Request Forgery (SSRF) flaws can occur when an API is fetching a remote resource without validating the user-supplied URI. 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. | | **API8: Security Misconfiguration** | APIs and the systems supporting them typically contain complex configurations, meant to make the APIs more customizable. Software and DevOps engineers can miss these configurations, or don't follow security best practices when it comes to configuration, opening the door for different types of attacks. | | **API9: Improper Inventory Management** | APIs tend to expose more endpoints than traditional web applications, making proper and updated documentation highly important. A proper inventory of hosts and deployed API versions also are important to mitigate issues such as deprecated API versions and exposed debug endpoints. | | **API 10: Unsafe Consumption of APIs** | Developers tend to trust data received from third-party APIs more than user input, and so tend to adopt weaker security standards. In order to compromise APIs, attackers go after integrated third-party services instead of trying to compromise the target API directly. | *Source:* https://owasp.org/API-Security/editions/2023/en/0x11-t10/