## OWASP Top 10 API Security Vulnerabilities and Runtime Detection This document outlines the OWASP Top 10 API Security vulnerabilities and provides guidance on how to detect them at runtime using API logs. We'll use the provided API log format as a reference for detection methods. ## API1:2023 - Broken Object Level Authorization Broken Object Level Authorization occurs when an API fails to properly verify that a user is authorized to access or manipulate specific resources. **What's considered a successful attack?** Typical methods involve changing an ID somewhere where the user can input information whether in an input form, URLs, Cookies, etc. When the attacker tries to change this ID, the API does not check whether a user owns a resource before that user can do anything to it ![Screenshot from 2024-10-18 05-38-09](https://hackmd.io/_uploads/rJAmtQkxyg.png) Many tools do not know that the userId in the query parameter and the userId in the cookie/JWT auth should match. This kind of detection requires the analysis of large amounts of API traffic in order to gain context and understand the normal behavior of each API. **Prevention** - Prefer the use of random and unpredictable values as GUIDs for records' IDs. - Zero trust business model. Once the user has been authenticated, the authorization mechanisms in place determine whether the user is allowed to access the requested resource. ## API2:2023 - Broken Authentication This vulnerability arises when authentication mechanisms are implemented incorrectly, allowing attackers to compromise authentication tokens or exploit implementation flaws. **What's considered a successful attack?** Weak authentications happen due to many factors, some of which are related to weak Passwords and Insecure JSON Web token (JWT) configuration, such as use of weak digital signature algorithm or missing signatures. The attacker can then successfully do an account takeover. ![image](https://hackmd.io/_uploads/ByVx_QJx1e.png) **How to detect?** 1. We could check out the JWT token and see for details which makes it insecure. These details could be: - `alg` header is set to none. - Public key verification (Unsure) 2. Do we need to detect weak passwords? 3. We can detect brute forcing attempts over a period of time. **Prevention** • Treat credential recovery/forgot password endpoints with the same security measures as login endpoints (brute force protection, rate limiting, lockouts). • Require re-authentication for sensitive operations like changing account email or 2FA phone number. • Implement multi-factor authentication where possible. • Use account lockout/CAPTCHA mechanisms to prevent brute force attacks on specific users. Implement weak password checks. • Do not use API keys for user authentication. Reserve them only for API client authentication. Citations: [1] https://cheatsheetseries.owasp.org/cheatsheets/Authentication_Cheat_Sheet.html ## API3:2023 - Broken Object Property Level Authorization This vulnerability occurs when there's a lack of proper authorization validation at the object property level. **What's considered a successful attack?** Let's say for example, we have an API to purchase an order, but the status is `unpaid` yet. This object can be changed to `paid` and the API will presume that they have paid for the order. ![image](https://hackmd.io/_uploads/Sk1puQyx1g.png) **Detection:** - Unsure how would we detect this. **Prevention** • When exposing an object via an API endpoint, always validate that the user has proper access to the exposed object properties. • Avoid using generic methods like `to_json()` or `to_string()`. Instead, specifically select and return only the necessary object properties. ## API4:2023 - Unrestricted Resource Consumption This risk involves APIs that don't properly limit resource consumption, potentially leading to Ddos/DoS or increased operational costs. Another example would be, let’s talk about a password reset function. There’s no limit on the number of times you can reset your password, but the developers didn’t expect anyone to do so 100,000 times in an hour. Password history is kept, but once a day any passwords older than 30 days are dropped. In this scenario, an attacker could fill that password history storage by sending password reset requests too fast. ![image](https://hackmd.io/_uploads/SJiTYmyx1x.png) **Detection:** - Unusually high amount of requests in a short period of time without any rate limiting. **Prevention** - Rate limit detection. But not sure how we'd implement it at runtime. But can be implemented when authentication requests are sent too many times. ## API5:2023 - Broken Function Level Authorization This occurs when APIs fail to restrict access to certain functions based on user roles. **What's considered a successful attack?** Let’s say an application has an endpoint /api/{account}/users that lists the users in a particular account, but also has an endpoint /api/admin/users that list all the users in every account. If that second endpoint isn’t appropriately restricted, that would be a function level authorization issue. A second example involves an endpoint that supports multiple methods. The endpoint /api/products supports the GET method for any user so that all users can view the products available. The POST method is used to add or update products. If POST is not appropriately restricted, this would constitute a Broken Function Level Authorization vulnerability. ![image](https://hackmd.io/_uploads/Hymrq71eJe.png) **Detection:** **Prevention** - The enforcement mechanism(s) should deny all access by default, requiring explicit grants to specific roles for access to every function. ## API6:2023 - Unrestricted Access to Sensitive Business Flows Let’s say you have an ecommerce website and you’re selling shoes. The website is driven by a set of APIs. When a visitor views a pair of shoes, the web application pulls an image, price, and description of the item via the API to display for the visitor. Without any restrictions in place, a malicious attacker could access the API directly and pull all of the pricing information, i.e., price scraping. ![image](https://hackmd.io/_uploads/ByB6qm1xye.png) **Detection:** - It is tricky to detect this because it's tied to business logic. **Prevention** - We could block IPs or certain Agents. such as blocking all traffic from TOR exit nodes or from specific geographies, which can cut down on some of the more obvious malicious bot activity. ## API7:2023 - Server Side Request Forgery SSRF occurs when an API fetches a remote resource without validating the user-supplied URI. 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. **Basic SSRF**: This is the simplest form, where an attacker directly manipulates a URL to access internal resources or external services. For example, they might change a URL in your application to point to a sensitive internal server. **Blind SSRF**: In this case, the attacker doesn’t receive a direct response from the server, making it harder to detect. However, they can still infer the success of their attack by observing side effects, such as delays in the application’s response or changes in the server’s logs. **SSRF with Authentication Bypass**: Some applications have authentication mechanisms to protect internal resources. However, if these mechanisms are not properly implemented, an attacker can bypass them using SSRF. This can give them access to sensitive data or functionality that they shouldn’t have. **SSRF to Local File Inclusion**: This type of attack involves manipulating a request to read or include local files from the server’s file system. Attackers could gain access to configuration files, source code, or other sensitive information. **SSRF to Port Scanning**: Attackers can leverage SSRF to scan ports on internal systems, potentially discovering open services or vulnerabilities that can be exploited. ![image](https://hackmd.io/_uploads/HkZmjX1ekg.png) **Detection:** - Analyze the `http.request.path` and `http.request.headers` for attempts to make the server request internal or unauthorized external resources. - Look for unusual destination IPs or domains in outgoing requests. **Prevention** - Isolate the resource fetching mechanism in your network: usually these features are aimed to retrieve remote resources and not internal ones. Whenever possible, use allow lists of: - Remote origins users are expected to download resources from (e.g. Google Drive, Gravatar, etc.) - URL schemes and ports - Accepted media types for a given functionality - Disable HTTP redirections. - Use a well-tested and maintained URL parser to avoid issues caused by URL parsing inconsistencies. - Validate and sanitize all client-supplied input data. Do not send raw responses to client ## API8:2023 - Security Misconfiguration This vulnerability arises from improper configuration of APIs and their supporting systems. **Detection:** - Monitor for error responses (non-200 status codes) in `http.response.status_code` that might reveal system information. - Check for missing security headers in `http.response.headers`. - Look for overly verbose error messages in `http.response.body` that might expose system details. **Prevention** Here are key recommendations for securing API communications: 1. Use TLS encryption for all API traffic: - Encrypt all client-to-API server communications using TLS, regardless of whether internal or public-facing - Encrypt communications between API server and any downstream/upstream components 2. Restrict HTTP methods: - Explicitly define which HTTP verbs (GET, POST, etc.) are allowed for each API endpoint - Disable all other HTTP verbs not needed 3. Implement proper CORS and security headers for browser-based clients: - Set up Cross-Origin Resource Sharing (CORS) policy - Include relevant security headers (e.g. Content-Security-Policy) 4. Restrict incoming content types: - Only allow content types and data formats required for business/functional needs - Validate and sanitize all incoming data 5. Ensure uniform request processing: - Configure all servers in the HTTP chain (load balancers, proxies, backends) to process requests consistently - Avoid HTTP request smuggling/desync vulnerabilities By implementing these measures, you can significantly enhance the security of your API communications and protect against common vulnerabilities. [1] https://flowlet.app/blog/5-cors-headers-your-api-needs ![image](https://hackmd.io/_uploads/r1X6o7Jxyl.png) ## API9:2023 - Improper Inventory Management This risk involves issues with API versioning and documentation. **Detection:** - Monitor for requests to deprecated or non-existent API versions in the `http.request.path`. - Look for attempts to access debug endpoints or test functions that shouldn't be publicly available. **Prevention** - Inventory all API hosts and document important aspects of each one of them, focusing on the API environment (e.g. production, staging, test, development), who should have network access to the host (e.g. public, internal, partners) and the API version. - Inventory integrated services and document important aspects such as their role in the system, what data is exchanged (data flow), and their sensitivity. ![image](https://hackmd.io/_uploads/HJwL3mJlJx.png) ## API10:2023 - Unsafe Consumption of APIs This vulnerability occurs when developers trust data from third-party APIs without proper validation. **Detection:** - While this is primarily a client-side issue, you can monitor for unusual data patterns in `http.request.body` that might indicate compromised third-party data. - Look for unexpected data formats or content in responses that might be consumed by other parts of your system. **Prevention** - When evaluating service providers, assess their API security posture. - Ensure all API interactions happen over a secure communication channel (TLS). - Always validate and properly sanitize data received from integrated APIs before using it. - Maintain an allowlist of well-known locations integrated APIs may redirect yours to: do not blindly follow redirects. ![image](https://hackmd.io/_uploads/r1_o27Jx1e.png) Citations: [2] https://owasp.org/API-Security/editions/2023/en/0x11-t10/ [3] https://www.postman.com/api-platform/api-security/ Some Analysis required on Sentryflow logs for OWASP Top 10: 1. Broken Object Level Authorization - Check the authorization/JWT header token and see if the user is accessing another user's resources. 2. Broken Authentication - Check JWT's alg header, if this is empty, the token is not valid. 3. Broken Object Property Level Authorization - Could check if the IP where this request originates from is outside the enviroment. 4. Unrestricted Resource Consumption - Rate limit detection through observability API. Check the timestamp and number of events. 5. Broken Function Level Authorization - This usually means someone accessing a privileged endpoint. How would be check what's a privileged endpoint and what's not? 6. Unrestricted Access to Sensitive Business Flows - N/A 7. Server Side Request Forgery - Check for client-supplied input data sanitization. Not too tough to check for sanitization. This could also work for XSS and SQLi 8. Security Misconfiguration - Internal error revealing internal code. Not something we can check everywhere. 9. Improper Inventory Management - Old APIs get exploited if not depricated by newer APIs. Can't check for this using sentryflow 10. Unsafe Consumption of APIs - Santization of Data to be checked to prevent SQLi, XSS, SSRF, etc. Can be done by sanitizing Request body.