Best Practices to Secure Your API
Explore various risks associated with API vulnerabilities while learning common API security best practices to implement robust security mechanisms.
Join the DZone community and get the full member experience.
Join For FreeAn Application Programming Interface (API) is a set of protocols that allow software components to interact. The intermediary interface is commonly used for streamlining development by enabling software teams to reuse code. APIs also abstract functionality between systems by decoupling applications from the infrastructure they run on. Though APIs’ benefits and use cases in modern business continue to rise, inherent security challenges present various security risks.
This article delves into various risks associated with API vulnerabilities while learning common API security best practices to implement robust security mechanisms.
What Is API Security?
An API represents a set of services that allow one program to communicate with another external or internal program. When we talk about API security, we typically refer to securing an application’s backend services, including its database, user management system, or other components interacting with the data store.
API security encompasses the adoption of multiple tools and practices to protect the integrity of a tech stack. A robustly secured API covers both the APIs an organization uses and the services that use them. This includes preventing malicious actors from accessing sensitive information or taking actions on your behalf that you did not intend them to perform. Unfortunately, while APIs are a crucial part of modern applications, they are a common target of attackers to access sensitive information.
It is crucial to understand how third-party applications funnel data through the interface when using APIs. Furthermore, with APIs increasingly becoming an attack vector, API security measures help security teams to assess security risks and have a comprehensive plan to protect them.
Risks of API Vulnerabilities
As APIs are publicly accessible, they are common targets to steal sensitive information, including application logic, user credentials, credit card numbers, etc. In addition, vulnerabilities in an API endpoint are also exploited by malicious actors to gain unauthorized access to a system or network for other forms of attacks such as cross-site scripting and code injections. The Online Web Application Security Project (OWASP) issues risk-based recommendations on the top 10 vulnerabilities to secure web API. These include:
- Broken User Authentication — Basic authentication presents a unique challenge in APIs since multi-factor authentication and credential-based logins are often considered impractical for API calls. As APIs rely on session tokens embedded into the calls to authenticate clients, APIs with insufficient authentication, such as faulty access token implementation, allow hackers to assume the identity of legitimate users. On the other hand, long-lived tokens also allow the attacker to persist, compromising the system indefinitely.
- Broken Object Level Authorization — In APIs, object-level authorization is a code-level control mechanism used to validate object access. For APIs with broken object-level authorization vulnerabilities, an external user can substitute the ID of their own resource with the ID of another user’s resource. This allows attackers to access the specified user’s resource, leading to unauthorized access of sensitive data.
- Lack of Resource and Rate Limiting —When the API does not limit the number and frequency of requests from a particular client, they could make numerous calls per second. The API client can also request access to multiple resources and records at once, overloading the application server to service multiple requests instantly. This can lead to Denial-of-Service attacks since a client making too many requests at once hinders the ability of the server to process requests. Lack of rate-limiting also encourages hackers to perform brute-force attacks on authentication endpoints.
- Mass Assignment — The mass assignment vulnerability occurs in APIs that automatically pipes user input to objects or program variables. While this feature simplifies code development, some users can initialize and over-write server-side variables, compromising the application. Attackers mostly exploit this by guessing and providing additional object properties when crafting requests. They can also read the application’s documentation or identify weak API endpoints that allow them to modify server-side objects.
- Security Misconfigurations — Multiple security misconfigurations pose a threat to APIs. These include:
- Verbose error messages — Some APIs send descriptive error messages containing stack traces and system information, keeping the user informed on how the application works under the hood.
- Misconfigured HTTP Headers expose security gaps that hackers can use to exfiltrate data and perform deeper sophisticated attacks.
- Unnecessary HTTP methods and services — If administrators fail to close down unnecessary services, malicious attackers can modify posted resources using different HTTP methods.
- Insecure default configurations — APIs connect with third-party dependencies, many of which are insecure by default and require an enhanced security posture to deal with a widened attack surface.
API Security — Best Practices to Consider
The following web API security best practices can help mitigate API attacks:
Use Throttling and Rate-Limiting
Throttling involves setting a temporary state that allows the API to evaluate every request and is often used as an anti-spam measure or to prevent abuse or denial-of-service attacks. There are two primary considerations when implementing the throttling feature: how much data should be allowed per user, and when should the limit be enforced?
On the other hand, rate-limiting helps administer REST API security by avoiding DoS and Brute force attacks. In some APIs, developers set soft limits, which allow clients to exceed request limits for a brief duration. Setting timeouts is one of the most straightforward API security best practices as it can handle both synchronous and asynchronous requests. Request queue libraries enable the creation of APIs that accept a maximum number of requests then put the rest in a waiting queue. Each programming language comes with a queue library directory to implement request queues.
Scan for API Vulnerabilities
To maintain the continuous security of API services, it is vital to enable automatic scanning, identify vulnerabilities, and mitigate them across software lifecycle stages. Automated scanning tools autonomously detect security gaps by comparing the application’s configuration against a known vulnerabilities database.
Use HTTPS/TLS for REST APIs
HTTPS and Transport Layer Security (TLS) offers a secured protocol to transfer encrypted data between web browsers and servers. Apart from other forms of information, HTTPS also helps to protect authentication credentials in transit. As one of the most critical practices, every API should implement HTTPS for integrity, confidentiality, and authenticity.
In addition, security teams should consider using mutually authenticated client-side certificates that provide extra protection for sensitive data and services. When building a secure REST API, developers should avoid redirecting HTTP to HTTPS, which may break API client security. Adequate steps should also be taken to divert Cross-Origin Resource Sharing (CORS) and JSONP requests for their fundamental vulnerabilities for cross-domain calls.
Restrict HTTP Methods
REST APIs enable web applications that execute various possible HTTP verb operations. Data over HTTP is unencrypted, using some HTTP methods may be intercepted and exploited by attack vectors. As a recommended best practice, HTTP methods (GET, PUT, DELETE, POST, etc.) that are inherently insecure should be forbidden. If a complete forbidding on their usage is not possible, security teams can also apply policies to vet the use of such methods with a strict allow list, whereby all requests that do not match the list should be rejected.
It is also recommended to utilize RESTful API authentication best practices to ensure that the requesting client can use the specified HTTP method on the action, record, and resource collection.
Implement Sufficient Input Validation
In principle, data supplied by the API client should not be trusted blindly since the authentication server may end up executing a malicious script from unauthorized users or application services. To avoid this, security teams should implement input validation mechanisms on both the client and server-side to prevent unhealthy input.
While client-side validation involves interactive indication of errors and advice to a user on acceptable inputs, a server-side validation additionally checks the data received to avoid the different types of XSS and SQL Injection attacks.
Use an API Gateway
An API gateway decouples the client interface from the collection of backend APIs, delivering a centralized resource for consistent availability and scalability of API services. Apart from managing various API services, the API management platform also handles standard functions, including telemetry, rate limiting, and user authentication, to maintain security between internal services. The gateway acts as a reverse proxy gatekeeper that accepts all API calls, coordinates the resources required to service them, and returns the appropriate results post-authentication.
Published at DZone with permission of Sudip Sengupta. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments