API Security - Best Practices and Checklist

Recently API’s (Application Programming Interface) are becoming hot cakes. Implementing API for your application is no more a niche thing but became essential. With advent of multi-faceted application interface (i.e Mobile Apps, Desktop Apps, Web Apps and Other Consumer applications). Its a great tool to expose your application consumption via own and third-party developers looking to integrate with your app. This enhances your audience reach and aid to consumers.

API Security - Best Practices and Checklist

Unfortunately, Application Programming Interface also gives additional opportunity to hackers to know internals of your application, hence providing another means to information exploitation.

In this article; we will cover fundamentals of API Security, common threats posed against APIs and ways to fortify (secure) and build defence against those threats. This will enable you to reap benefits of APIs without its downsides.

What Is API Security?

API Security is the practice of protecting API endpoint(s) from cyberattacks and misuse. Appropriate API Security defence mechanisms ensures that all request(s) made to API endpoint are verified and from legitimate sources. It also ensures that all responses are protected from exploitation and interceptions.

The usual objective of API is to promote the transfer of data (which may be private in some cases) between your application and its consumers. Consequently a loosely (un)secured API can prove to be a golden treasure for hackers and nightmare for you.

If these claims alarms you, you should know that billions of private data have been exposed through cyberattacks that exploited insecure API endpoints

API Security - Best Practices and Checklist - Data Breach/Compromise Year Wise

Outstanding API exploitation have been affecting enterprises across globe (including Fortune 500, Facebook, Twitter, Sony etc.). To protect your API from being exploited and stripped of sensitive data, you’ll need to implement API Security principles to fortify your API endpoint(s). There are three phases of application security as described below

  • Intrusion Prevention System: An IPS, on the other hand, is designed to take action to block anything that it believes to be a threat to the protected system. As malware attacks become faster and more sophisticated, this is a useful capability because it limits the potential damage than an attack can cause. An IPS is ideal for environments where any intrusion could cause significant damage, such as databases containing sensitive data

  • Intrusion Detection System: An IDS is designed to detect a potential incident, generate an alert, and do nothing to prevent the incident from occurring. While this may seem inferior to an IPS, it may be a good solution for systems with high availability requirements, such as industrial control systems (ICS) and other critical infrastructure. For these systems, the most important thing is that the systems continue running, and blocking suspicious (and potentially malicious) traffic may impact their operations. Notifying a human operator of the issue enables them to evaluate the situation and make an informed decision on how to respond.

  • Incident Response System: Incident response (sometimes called cybersecurity incident response) refers to an organization’s processes and technologies for detecting and responding to cyberthreats, security breaches or cyberattacks. The goal of incident response is to prevent cyberattacks before they happen, and to minimize the cost and business disruption resulting from any cyberattacks that occur.

Why API Security Is Important

Although CyberSecurity is very vast topic that includes all online technologies, but APIs has its unique and broad sets of challenges as it acts as middleman between third-party applications and applications resources. API security breach can be more harmful given that it exposes applications exposed architecture. Having hacked API endpoint can grant direct access to many sensitive and private data (given how its been implemented)

Moreover, think about financial impact of data breach through API endpoint? It can be substantial and can also hamper your brands image to the extent of failure.

Types of API Cyberattacks

Before diving into the API Security Checklist or best practice to follow; we need to gauge what type of attacks are expected. Below are the most common attacks reported against APIs that we know about

Stolen Authentication

Stolen Authentication has been most common attack that has always been around is, accessing API endpoint by “Stolen Identity” of registered consumer. Cybercriminals will try to steal identity of authorized consumer of API or they can also try to break in by brute force. It can also be easier to break-in for cybercriminals if authentication process employed is weak of have known vulnerability.

Man-in-the-Middle Attack

According to OWASP, Man-In-The-Middle (MITM) attack is one of the most common attack. Cybercriminals or hacker can intercepts an API request or response between API and its consumer. Thus, impersonating by requesting with forged request with active session to gain illegitimate access. This way they can be able to steal sensitive data of consumer(s)

To understand this in simple terms, assume a mailman opening a bank statement envelop, noting down confidential information, resealing the envelop and delivering to you and vice versa.

Code Injections

According to OWASP, Code Injection is one of the Top 10 cyberattacks. This happens when, APIs are using software with know vulnerability or have gaps in authentication, validations. Hacker; then sends malicious code into application via API endpoint. This code can then delete, insert, update or expose sensitive data to hacker. Consequently sensitive data exposed can be used to harm application or its consumer(s)

“SQL Injection” is still most common used Code Injection that can be used expose entire database.

Denial-of-Service Attack

Denial-of-service (DoS) attacks application server to overwhelm or consume its resources with flooding automated requests, thus slowing breaking or crashing the application. If application leverage auto spawn cloud on demand, then this can result in highly inflated bills. Frequently these attacks are initiated from multiple malicious automated sources simultaneously and thus called DDoS (Distributed Denial of Service) Attack.

To understand this in simple terms, think of made up traffic jams; where people knowingly came to streets just to create jam and obstruct driving to airport to intentionally delay them.

Despite all the risks stated above, APIs are backbone of internet these days and are not going to disappear any soon. APIs are needed for applications to connect smoothly at programming level, thus every new application exposing APIs are another opportunity for cybercriminals to exploit. Therefore it is paramount for developers developing APIs or consuming it to fully understand API security to safeguard against these threats.

API Security - Best Practices and Checklist

API Security Best Practices / Checklist

While any applications API can be targeted by cybercriminals; but application with huge user-base are going to be targeted first. Secondly each application with APIs will implement API Security differently depending upon the purpose they serves. Security measures varies from API for payment gateway then to a content sharing service. Security checklist provided in this article are general in nature and applies to all application transferring data over HTTP(S); implementing REST or GraphQL API endpoints.

These measures are also applicable to application implementing micro-services for intra application communications.

By following the guidelines below, you’ll greatly mitigate risks that are generally associated with maintaining an API server, no matter your niche.

Implement Authentication

Before processing an API endpoint request, an API must perform authentication to establish identity of consumer or application program that initiated the request. For this, APIs employ different kind of authentication mechanisms (i.e password, basic authentication, JW token authentication). Further to this APIs can employ multi-factor authentication to have layered authentication mechanisms.

Presently, the OAuth and JWT protocol is the widely accepted as standard for API user/client authentication. [OAuth] was originally designed for Single Sign On (SSO), social login, allowing users to log into third-party applications without revealing their passwords. For example, OAuth lets you use your Google password to sign into a third-party website like Twitter, Facebook etc., without requiring Twitter, Facebook to store your passwords. Read more regarding OAuth 2.0

While JWT on other hand is an open standard, that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the HMAC algorithm) or even a public/private key pair using RSA or ECDSA. JWT has many advantage, vast range of encryption algorithms to choose from, expiration, claims like issuer, subject, audience, not before, issued at etc, to secure it further.

OAuth is built on HTTP, which also makes it a great fit for REST APIs. While the inner-workings of OAuth are beyond the scope of this article, on a basic level OAuth gives API administrators a way to grant authentication tokens to approved third parties. Admins can set custom access rules that determine which API requests are permitted, based on the source of the request.

Implement Authorization

After verification of identity of client, next step is to validate authorization of client for resource user is requesting access to. Let’s take an example to understand it better; client A has access approved to read email, however it does not have access to send email on user’s behalf. Any attempt to access to endpoint that is not unauthorized for client should be rejected. Authorization information can also be contained within a request as a token.

API Security - Best Practices and Checklist - Authorization

In contrast to, other API implementation, REST APIs must authenticate and authorize each request made to the server, even if multiple requests come from the same client. This is because RESTful communications are stateless. That means, each API request needs to be treated in isolation, irrespective of concurrent requests from same client.

Authorization shall be governed by client roles, where each role comes with different set of permissions. In general, API developers should adhere to the principle of least privilege, which states that client should only have access to the resources and methods necessary for their role assigned, and nothing more. Predefined roles make it easier to oversee and change client permissions, reducing the chance that a bad actor accessing sensitive data.

Validate all API Requests

As mentioned in MITM attack, sometimes request seems to be coming from valid source maybe an attempt to hack resources. Consequently, API need set of rules in place to determine, whether a request is genuine, genuine but not valid or harmful.

An API request is only processed once its contents pass a thorough validation check. Otherwise, the request should never be able to reach the application’s data layer.

Encrypt Data

As mentioned in MITM attack, to prevent such attacks; any data transfer from the client to the API server or vice versa must be properly encrypted. This way, any intercepted requests or responses are useless to the intruder without the right decryption keys to be able to decipher the packets.

Since REST APIs leverage HTTP, encryption can be attained by using the Transport Layer Security (TLS) protocol or its previous version, the Secure Sockets Layer (SSL) protocol. These protocols add the S in “HTTP”, and are the current standard for encrypting web pages and REST API communications.

API Security - Best Practices and Checklist - Encryption

There are many CMS platforms that provides a free SSL that will encrypt your pages from day one. But if your platform does not offer an SSL like WordPress, you can still add one from other vendors.

TLS/SSL only encrypts data when that data is being transferred. It doesn’t encrypt data sitting behind your API, which is why sensitive data in database should always be encrypted in the database layer as well. There are many database encryption methods out there depending upon database you are using

Along with an SSL, consider integrating a Web Application Firewall (WAF) that will monitor web traffic to identify and prevent DDoS attacks and code injections.

Do not overshare Information

If unnecessary or additional information added to API response, it is possible that we expose information that hacker can use to their aid. As a prevention, API response should include information that is necessary for that request, success or failure messages. Strictly avoid oversharing of data to prevent inadvertently exposing private or structural data either via resources or verbal errors or statuses

Implement Throttle API or Quotas

Rate-limiting is employed by all APIs to encounter DDoS like attacks. Rate-limiting is throttling or denying requests; depending on strategy used, from client if they cross prescribed safe request limit in specified time. This is a must to prevent several brute-force attacks.

There are two major strategy to rate-limit API requests, Quotas and Throttling. Quotas limit the number of requests allowed from a client over a span of time, while throttling slows a client’s connection while still allowing them to use your API.

Both methods should allow normal API requests but prevent floods of traffic intended to disrupt, as well as unexpected request spikes in general.

Log API activity

Up until now we discussed “Prevention” method of “Prevention”, “Detection” and “Response” of system security. “Detection” of breach extremely critical . In the case of successful breach by hackers, it is vital that we will be able trace the source of incident(s) to plug the breach and avoid further breach of similar kind.

This is where logging all API server activity is essential to know what actions were executed, how and by whom. This will tell us how breach has happened. Equipped with this information we can plug the breach and harden our defences of API to prevent similar incidents in future.

Conduct Security Tests

We should not wait until an actual incident to see how our safeguard hold up. Instead there are many security test software out there using which we can mock test our safeguards. These security test softwares can launch mock most widely used attacks on systems and give us reality checks against most commonly used attack tactics. These tests should be performed on regular intervals, on every production updates. These test will help us to find out any unintentional gap has been left in system security.

Let’s take a closer look at this step below.

API Security Testing

The first step of API security is ensuring that your API is working as expected. That means submitting normal requests via an API Client and making sure they stick to the principles above. Develop scenarios that answer the following:

  • Can only authenticated users access your endpoints?
  • Are users granted access to only the necessary endpoints based on their roles?
  • Is the correct information returned in responses for each potential request?
  • Are benign but invalid requests rejected?

Once you’ve established that your API is working normally, you’ll need to simulate code injection, MITM, DoS, and stolen password and various other attacks against your systems in a proper testing environment. Below are some specific tests you can run.

User Authentication Test

To test your authentication mechanisms, try sending API requests without proper authentication (either no tokens or credentials, or incorrect ones) and see if your API responds with the correct error and messaging.

Parameter Tampering Test

To run a parameter tampering test, try various combinations of invalid query parameters in your API requests and see if it responds with the correct error codes. If not, then your API likely has some backend validation errors that need to be resolved.

Injection Test

To test if your API is vulnerable to injections, try injecting SQL, NoSQL, LDAP, OS, or other commands in API inputs and see if your API executes them. These commands should be harmless, like reboot commands or cat commands.

Unhandled HTTP Methods Test

Most APIs have various HTTP methods that are used to retrieve, store, or delete data. Sometimes web servers will give access to unsupported HTTP methods by default, which makes your API vulnerable.

To test for this vulnerability, you should try all the common HTTP methods (POST, GET, PUT, PATCH, and DELETE) as well as a few uncommon ones. TRY sending an API request with the HEAD verb instead of GET, for example, or a request with an arbitrary method like FOO. You should get an error code, but if you get a 200 OK response, then your API has a vulnerability.

Fuzz Test

Fuzz testing should be one of the last steps of your API security auditing process. This type of testing requires your API to be pushed to its limits in order to discover any functional or security issues that have yet to be revealed.

To achieve this, send a large number of randomized requests, including SQL queries, system commands, arbitrary numbers, and other non-text characters, and see if your API responds with errors, processes any of these inputs incorrectly, or crashes. This type of testing will mimic Overflow and DDoS attacks.

There are many tools available in market that can simulate various tailor-made attacks against your API for you to test it against them. Some of them are listed below

Author’s note: This post was originally published in December 2018 and has been updated for comprehensiveness.

About The Author

I am Pankaj Baagwan, a System Design Architect. A Computer Scientist by heart, process enthusiast, and open source author/contributor/writer. Advocates Karma. Love working with cutting edge, fascinating, open source technologies.

  • To consult Pankaj Bagwan on System Design, Cyber Security and Application Development, SEO and SMO, please reach out at me[at]bagwanpankaj[dot]com

  • For promotion/advertisement of your services and products on this blog, please reach out at me[at]bagwanpankaj[dot]com

Stay tuned <3. Signing off for RAAM