APIs are a strategic necessity to give your business the agility, innovation and speed needed to succeed in today’s business environment. However, the financial incentive associated with this agility is often tempered with the fear of undue exposure of the valuable information that these APIs expose.
With the rise of APIs also comes the potential for more security holes, meaning coders need to understand the risk to keep corporate and customer data safe. According to Gartner, by 2022, API abuses will be the most–frequent attack vector for enterprise web applications data breaches. It is no wonder that many IT decision makers today are concerned about API security.
In 2018 itself, there have been more than a half dozen headlines of data breaches where APIs were listed as the exploited mechanism to illegally extract data. Hackers are sophisticated and are constantly looking into new ways to break down defenses and access valuable data. Taking the appropriate security measures throughout the design process can ensure that your API is used properly by those you allow to interact with your application.
Let’s look at the best practices and strategies for securing APIs. If you are building an API for public use or even only for your internal services, the following 22 secure coding practices are to be considered before augmenting any additional security layer or technology: Authentication –API authentication means determining that the client application has an identity that is allowed to use the API. API must be able to authenticate itself to the Apps which consume it. Likewise, when your API interacts with Servers, they must authenticate themselves to the API. Tokens should expire regularly to protect against replay attacks. Most enterprises will use an internal database or LDAP authentication store, though Oath may be a better option for highly public APIs.
Multi–factor Authentication (MFA) – Multi–factor Authentication (MFA) requires a user to use a one–time usage token they receive after authenticating with her credentials. The User may also have a digital key which is a token that the App can validate. When the App receives the token which it validates with the MFA Provider, it proceeds to consume your API. Tokens are usually issued with an expiration period and can be revoked.
Authorization – Authorization is determining the scope of interaction allowed – that is, what actions and data the authenticated application has access to when using the API. This is typically best handled by application logic for e.g. using an access control framework, such as OAuth. However, it is best to augment this functionality using an API gateway. The following two ways are also used for defining level of authorization required by the user –
- Role–based Access Control (RBAC) – Static assignment of roles to Users based on the organizational groups to which they belong. Groups are role and App agnostic, they are purely business–level decisions. In RBAC an App uses roles to assign degrees of access to groups of Users which the role represents.
- Attribute–based access control (ABAC) – Attribute–based Access Control (ABAC) aims to facilitate the dynamic determination of access control based on some sort of circumstantial information available at the time of the API call.
- Make security the number one priority – Developers often have a feature–driven mindset, where functionality has taken precedence over security. Unfortunately, in today’s security landscape, vulnerabilities and threats lurk at every corner and have ever–growing consequences, so we have to turn this on its head.
- Encryption – SSL/TLS encryption is mainstream and should be used for both public and internal APIs to protect against man in the middle attacks, replay attacks, and snooping. For external APIs the web server can handle this directly or a reverse proxy can be employed. A service mesh can be used for internal APIs libraries to add automatic encryption on top of service discovery and routing.
- Protecting your API – Developers must ensure that the API properly validates all input from the user to prevent XSS and SQL Injection. There are many ways to protect against these types of vulnerabilities including but not limited to “cleaning user input to prevent XSS”, as well as preventing SQL Injection by “preparing statements with bind variables”.
- Block Large Requests and Responses – Some attackers may try to overwhelm the API or trigger a buffer overflow vulnerability with large requests. These may be in the form of a large JSON body or even unusually large individual JSON parameters within the request. Abnormally large response may also be indicator of data theft. Create custom rules to track and block these suspicious requests. A web application firewall can automatically detect and blocks this type of input abuse.
Throttling your API – Throttling is a means of controlling or limiting a client’s access to your data. There are two key API throttles that will provide you with additional control & security for your APIs: IP–based throttling – Using IP–based throttling you can restrict the number of API calls made by a particular IP address. In addition, you could ensure that your API can only be accessed by a particular set of IP addresses.
Rate–limit throttling – Rate–limit throttling allows API requests to be made until a certain limit has been reached for a specific time period. By utilizing rate–limit throttling within your API you can help to ensure that the database isn’t overwhelmed by one particular client who may be misusing your interface.
Building tests that don’t represent real functional use – Performing tests without considering how the APIs will be consumed may be quicker in the short–term. However, in doing so, you won’t be testing across concerns, which could prevent you from uncovering and debugging potentially serious API issues.
Custom API Rules – Build your own business logic rules for security, for e.g. a simple protection might be to identify your authentication token (in the HTTP header or in the JSON body) and require it to always be present to block and log any unauthenticated attempts. Another example would be to enforce the Content–Type header to be what is expected for your API (e.g. application/json) or block unused or non–public HTTP methods (e.g. PUT and DELETE) to further lock down the API.
Testing APIs in a vacuum – Building API tests can be a bit of a solo act, but the minute a test is in your workflow, it requires the attention of different teams in your organization. If you set up test failure notifications to go to just you, you’re adding time, effort and headaches to your workflow.Keys in URI – For some use cases, implementing API keys for authentication and authorization is good enough. However, sending the key as part of the Uniform Resource Identifier (URI) can lead to the key being compromised. As explained in IETF RFC 6819, It’s safer to send API keys is in the message authorization header, which is not logged by network elements. As a rule of thumb, the use of the HTTP POST method with payload carrying sensitive information is recommended.
Geofencing – If your API is public, it might make sense to either block users from countries you don’t do business with, or at least raise the risk score of entities that come from those countries.
API Fuzzing Protection – You may have a combination of documented and undocumented features in your APIs. Attackers may attempt to map and exploit the undocumented features by iterating or fuzzing the endpoints. Install a web application firewall for application profiling and behavior tracking.
L7 DOS Protection – You have protected the front–end of the API with rate–limiting, but the back–end services can still be exposed to Layer 7 denial of service. Customize a web application firewall to ensure long–running queries gets tarpitted and eventually blocked automatically.
Use Auditing and Logging – Auditing should never be skipped. Logging should be systematic and independent, and resistant to log injection attacks. Auditing should be used as a tool for detecting and proactively preventing attacks.
Monitor add–on software carefully – One popular use of the interfaces is to allow third parties to write add–on apps for a platform. A potential monster is such interfaces often give developers a high level of authorization rights. Hackers covet those privileges and will voraciously try to dig out such system vulnerabilities.
Secure the exit gateways – Businesses need to set up another checkpoint on the way out of the network. Even If a hacker worms into the system and accesses confidential information, it has value only if the data can be moved out to their own systems. In other words, if you miss a crook on the way in, you still can thwart him on the way out.
Stack Trace – Many API developers become comfortable using 200 for all success requests, 404 for all failures, 500 for some internal server errors, and, in some extreme cases, 200 with a failure message in the body, on top of a detailed stack trace. A stack trace can potentially become an information leak which attackers can exploit by submitting crafted URL requests. It’s a good practice to return a “balanced” error object, with the right HTTP status code, with minimum required error message(s) and “no stack trace” during error conditions. This will improve error handling and protect API implementation details from an attacker.
Consider Adding Timestamp in Request – Along with other request parameters, you may add a request timestamp as HTTP custom header in API request. The server will compare the current timestamp to the request timestamp, and only accepts the request if it is within a reasonable timeframe (1–2 minutes, perhaps). This will prevent very basic replay attacks from people who are trying to brute force your system without changing this timestamp.
Design Guidelines for Developers – DevOps has made allocating resources simpler and faster, but at the same time, being under pressure to deliver new releases ASAP, well intentioned, responsible programmers sometimes hurry and make mistakes. Here are design guidelines for developing secured APIs:
- Drop Basic Authentication Instead, use a more secure method such as JWT or OAuth.
- Don’t ship a home–grown solution
- Never expose information or URLs
- Implement Max Retry and Jail safety mechanisms
- Encrypt Everything
- Limit Requests
- Enforce HTTP Methods
- Validate User–Submitted Content
- Remove Components with Vulnerabilities
- Protect Sensitive Endpoints
- Avoid Using Auto–Incrementing IDs
- Apply strict input validation
- Use Password Hash
- Turn Debug Mode Off
- Logging & Monitoring
API usage is rising and empowering businesses to build more dynamic applications. However, as they take advantage of these capabilities, organizations need to be aware of the potential security holes, close them timely and ensure that security is the number one priority.
An unsecured API / application endpoint can serve as a gateway to the data centre by which attackers can effectively attack the backend and there is no silver bullet when it comes to its security.
Goal of this article is to make developers understand design principles and security best practices, to protect their APIs from malicious activity. Potential threats can often be avoided by thinking critically about these practices and applying them to avoid breaches and help your business maximize its potential.