Need to generate API key for different application - api-key

I have developed API in dot net. This API is consumed by different application. I have to generate a different key for each application which is consumed by this API. Can anyone please share their Ideas. This is first time i am doing such tasks.

Your Problem
I have developed API in dot net. This API is consumed by different application. I have to generate a different key for each application which is consumed by this API.
When creating an API, no matter if consumed by one or more applications you need to deal with the fact of WHAT is accessing the API and sometimes you also need to care about WHO is accessing it.
With this in mind lets clear a common misconception among developers about WHO and WHAT is accessing an API server.
The Difference Between WHO and WHAT is Accessing the API Server
I don't know if the applications consuming the API are mobile or web based, but I will do my analogy using a mobile application, and for a web application the difference between WHO and WHAT will make no difference.
To better understand the differences between the WHO and the WHAT are accessing a mobile app, let’s use this picture:
The Intended Communication Channel represents the mobile app being used as you expected, by a legit user without any malicious intentions, using an untampered version of the mobile app, and communicating directly with the API server without being man in the middle attacked.
The actual channel may represent several different scenarios, like a legit user with malicious intentions that may be using a repackaged version of the mobile app, a hacker using the genuine version of the mobile app, while man in the middle attacking it, to understand how the communication between the mobile app and the API server is being done in order to be able to automate attacks against your API. Many other scenarios are possible, but we will not enumerate each one here.
I hope that by now you may already have a clue why the WHO and the WHAT are not the same, but if not it will become clear in a moment.
The WHO is the user of the mobile app that we can authenticate, authorize and identify in several ways, like using OpenID Connect or OAUTH2 flows.
OAUTH
Generally, OAuth provides to clients a "secure delegated access" to server resources on behalf of a resource owner. It specifies a process for resource owners to authorize third-party access to their server resources without sharing their credentials. Designed specifically to work with Hypertext Transfer Protocol (HTTP), OAuth essentially allows access tokens to be issued to third-party clients by an authorization server, with the approval of the resource owner. The third party then uses the access token to access the protected resources hosted by the resource server.
OpenID Connect
OpenID Connect 1.0 is a simple identity layer on top of the OAuth 2.0 protocol. It allows Clients to verify the identity of the End-User based on the authentication performed by an Authorization Server, as well as to obtain basic profile information about the End-User in an interoperable and REST-like manner.
While user authentication may let the API server know WHO is using the API, it cannot guarantee that the requests have originated from WHAT you expect, the original version of the mobile app.
Now we need a way to identify WHAT is calling the API server, and here things become more tricky than most developers may think. The WHAT is the thing making the request to the API server. Is it really a genuine instance of the mobile app, or is a bot, an automated script or an attacker manually poking around with the API server, using a tool like Postman?
For your surprise you may end up discovering that It can be one of the legit users using a repackaged version of the mobile app or an automated script that is trying to gamify and take advantage of the service provided by the application.
Well, to identify the WHAT, developers tend to resort to an API key that usually they hard-code in the code of their mobile app. Some developers go the extra mile and compute the key at run-time in the mobile app, thus it becomes a runtime secret as opposed to the former approach when a static secret is embedded in the code.
The above write-up was extracted from an article I wrote, entitled WHY DOES YOUR MOBILE APP NEED AN API KEY?, and that you can read in full here, that is the first article in a series of articles about API keys.
Defending an API Server
Can anyone please share their Ideas.
A mobile app or a web app should only communicate with a API server that is under your control and any access to third part APIs services must be done by this same API server you control.
This way you limit the attack surface to only one place, where you will employ as many layers of defense as what you are protecting is worth.
For an API serving a web app you can employ several layers of dense, starting with reCaptcha V3, followed by Web Application Firewall(WAF) and finally if you can afford it a User Behavior Analytics(UBA) solution.
Google reCAPTCHA V3:
reCAPTCHA is a free service that protects your website from spam and abuse. reCAPTCHA uses an advanced risk analysis engine and adaptive challenges to keep automated software from engaging in abusive activities on your site. It does this while letting your valid users pass through with ease.
...helps you detect abusive traffic on your website without any user friction. It returns a score based on the interactions with your website and provides you more flexibility to take appropriate actions.
WAF - Web Application Firewall:
A web application firewall (or WAF) filters, monitors, and blocks HTTP traffic to and from a web application. A WAF is differentiated from a regular firewall in that a WAF is able to filter the content of specific web applications while regular firewalls serve as a safety gate between servers. By inspecting HTTP traffic, it can prevent attacks stemming from web application security flaws, such as SQL injection, cross-site scripting (XSS), file inclusion, and security misconfigurations.
UBA - User Behavior Analytics:
User behavior analytics (UBA) as defined by Gartner is a cybersecurity process about detection of insider threats, targeted attacks, and financial fraud. UBA solutions look at patterns of human behavior, and then apply algorithms and statistical analysis to detect meaningful anomalies from those patterns—anomalies that indicate potential threats. Instead of tracking devices or security events, UBA tracks a system's users. Big data platforms like Apache Hadoop are increasing UBA functionality by allowing them to analyze petabytes worth of data to detect insider threats and advanced persistent threats.
All this solutions work based on a negative identification model, by other words they try their best to differentiate the bad from the good by identifying what is bad, not what is good, thus they are prone to false positives, despite of the advanced technology used by some of them, like machine learning and artificial intelligence.
So you may find yourself more often than not in having to relax how you block the access to the API server in order to not affect the good users. This also means that this solutions require constant monitoring to validate that the false positives are not blocking your legit users and that at same time they are properly keeping at bay the unauthorized ones.
Regarding APIs serving mobile apps a positive identification model can be used by using a Mobile App Attestation solution that guarantees to the API server that the requests can be trusted without the possibility of false positives.
The Mobile App Attestation
The role of a Mobile App Attestation service is to guarantee at run-time that your mobile app was not tampered or is not running in a rooted device by running a SDK in the background that will communicate with a service running in the cloud to attest the integrity of the mobile app and device is running on.
On successful attestation of the mobile app integrity a short time lived JWT token is issued and signed with a secret that only the API server and the Mobile App Attestation service in the cloud are aware. In the case of failure on the mobile app attestation the JWT token is signed with a secret that the API server does not know.
Now the App must sent with every API call the JWT token in the headers of the request. This will allow the API server to only serve requests when it can verify the signature and expiration time in the JWT token and refuse them when it fails the verification.
Once the secret used by the Mobile App Attestation service is not known by the mobile app, is not possible to reverse engineer it at run-time even when the App is tampered, running in a rooted device or communicating over a connection that is being the target of a Man in the Middle Attack.
The Mobile App Attestation service already exists as a SAAS solution at Approov(I work here) that provides SDKs for several platforms, including iOS, Android, React Native and others. The integration will also need a small check in the API server code to verify the JWT token issued by the cloud service. This check is necessary for the API server to be able to decide what requests to serve and what ones to deny.
Summary
I think it should be pretty clear by now that you will need to use an API key for each application to identify the WHAT, and if you care about the WHO you should employ an OAUTH solution to, and then choose what defense layers you want to put in place on the API server to guarantee that you really know that the WHAT and the WHO is accessing the API server are really the ones you expect.
In the end the solution to use in order to protect your API server must be chosen in accordance with the value of what you are trying to protect and the legal requirements for that type of data, like the GDPR regulations in Europe.
So using API keys may sound like locking the door of your home and leave the key under the mat, but not using them is liking leaving your car parked with the door closed, but the key in the ignition.
Going the Extra Mile
This is first time i am doing such tasks.
So I real recommend you to read some links...
Web Apps
OWASP Web Top 10 Risks
The OWASP Top 10 is a powerful awareness document for web application security. It represents a broad consensus about the most critical security risks to web applications. Project members include a variety of security experts from around the world who have shared their expertise to produce this list.
Mobile Apps
OWASP Mobile Security Project - Top 10 risks
The OWASP Mobile Security Project is a centralized resource intended to give developers and security teams the resources they need to build and maintain secure mobile applications. Through the project, our goal is to classify mobile security risks and provide developmental controls to reduce their impact or likelihood of exploitation.

Related

how to secure an API when called by Android app

I have a series of JsonAPIs triggers within an Android app.
Question is:
If I have a token for auth. then app's users can easily capture the POST request and find the token, even if I hash the token within the app and send it to server, then compare it to the hashed token from DB users still can capture the hashed token...
Whats a true way to deal with this??
AUTH TOKENS
If I have a token for auth.
Please bear in mind that a User Auth token only identifies who is in the request, not what is doing the request. Don't worry if you were not aware of this yet, because its a very usual misconception among developers of any level and background.
So lets' clear it up first...
The Difference Between WHO and WHAT is Accessing the API Server
I wrote a series of articles around API and Mobile security, and in the article Why Does Your Mobile App Need An Api Key? you can read in more detail the difference between who and what is accessing your API server, but I will quote some of the main points from it:
The what is the thing making the request to the API server. Is it really a genuine instance of your mobile app, or is it a bot, an automated script or an attacker manually poking around your API server with a tool like Postman?
The who is the user of the mobile app that we can authenticate, authorize and identify in several ways, like using OpenID Connect or OAUTH2 flows.
So think about the who as the user your API server will be able to Authenticate and Authorize access to the data, and think about the what as the software making that request in behalf of the user.
EVERYTHING IN THE CLIENT CAN BE CAPTURED OR EXTRACTED
If I have a token for auth. then app's users can easily capture the POST request and find the token, even if I hash the token within the app and send it to server, then compare it to the hashed token from DB users still can capture the hashed token...
No matter what technique you use in the end an attacker can always get hold on any secret you try hard to hide from him, the question is more how much effort he is willing to put in getting it from your mobile app and/or how much knowledge he have to perform such tasks.
Nowadays we have a plethora of tools to help security researchers or anyone one with bad intentions to reverse engineer a mobile app, like:
For MitM atttacks - mitmproxy
An interactive TLS-capable intercepting HTTP proxy for penetration testers and software developers.
For static analysis - MobSF - Mobile Security Framework
Mobile Security Framework is an automated, all-in-one mobile application (Android/iOS/Windows) pen-testing framework capable of performing static analysis, dynamic analysis, malware analysis and web API testing.
For runtime code instrumentation - Frida
Inject your own scripts into black box processes. Hook any function, spy on crypto APIs or trace private application code, no source code needed. Edit, hit save, and instantly see the results. All without compilation steps or program restarts.
Despite this tools exist I still encourage you to employ as many defense techniques as you can afford into your mobile app, because not every attacker as the knowledge or is willing to spent too much time in your mobile app, when they have easier targets to attack.
POSSIBLE SOLUTION
Whats a true way to deal with this??
No true way exists, it's all about your special use case and how much resources you have and can afford to employ and are required by law to do so.
For APIs serving mobile apps you can employ the Mobile App Attestation concept that will allow your API server to have an high degree of confidence about what is doing the request to the API server, is it your genuine and untampered mobile app or is an attacker.
I recommend you to read this answer I gave to the question How to secure an API REST for mobile app?, specially the sections Securing the API Server and A Possible Better Solution.
DO YOU WANT TO GO THE EXTRA MILE?
In any response to a security question I always like to reference the excellent work from the OWASP foundation.
For Mobile Apps
OWASP Mobile Security Project - Top 10 risks
The OWASP Mobile Security Project is a centralized resource intended to give developers and security teams the resources they need to build and maintain secure mobile applications. Through the project, our goal is to classify mobile security risks and provide developmental controls to reduce their impact or likelihood of exploitation.
OWASP - Mobile Security Testing Guide:
The Mobile Security Testing Guide (MSTG) is a comprehensive manual for mobile app security development, testing and reverse engineering.
For APIS
OWASP API Security Top 10
The OWASP API Security Project seeks to provide value to software developers and security assessors by underscoring the potential risks in insecure APIs, and illustrating how these risks may be mitigated. In order to facilitate this goal, the OWASP API Security Project will create and maintain a Top 10 API Security Risks document, as well as a documentation portal for best practices when creating or assessing APIs.

How do I trust an application to use my access token?

So I grant access of my resource to application A, and that application gets that access token. It is just a string. Sometimes the application will pass that access token to its backend server, and then use it to retrieve my resource. Usually the access token is valid for say one month.
Now my question is, what if application A leaks my access token, so any application B can use that access token to get my resource, which is not what I want. I only want application A can access my resource, not application B.
How do we trust application and give it my access token?
YOUR PROBLEM
Usually the access token is valid for say one month.
Using 1 month to the access token expiration time is way to long, not matter if is for admin or normal users.
Depending on your use case I recommend you to use the access tokens with an expiration time in the range of minute, lesser time you can have better will be for security.
So I would recommend you to switch to use refresh tokens, that will keep the access tokens short lived while refresh tokens can be long lived, but in the hours range, not days, weeks or years.
Refresh Token flow example:
Sourced from: Mobile API Security Techniques - part 2
NOTE: While the above graphic belongs to a series of articles written in the context of mobile APIs, they have a lot of information that is also valid for APIs serving web apps and third party clients.
By using the refresh tokens approach, when a client request fails to validate the short lived access token will mean that the client needs to request a new one by sending a refresh token in order to get a new short lived access token.
The important bit here is that the refresh token should not be sent to the browser, only the access token can be sent, therefore your third party clients must kept refresh tokens private, aka in their backends, therefore they MUST NOT send refresh tokens from javascript, instead any renewal of the short lived acess tokens MUST BE delegated to their backends.
Now my question is, what if application A leaks my access token, so any application B can use that access token to get my resource, which is not what I want.
That's why you should use the Refresh Tokens approach I mentioned earlier, because you limit their access to the amount of time remaining in the access token, and this is why I said that the short lived access tokens should be in the range of minutes.
I only want application A can access my resource, not application B.
I am gonna tell you a cruel truth... this is not doable at 100%, specially for web apps, where you can just hit F12 to access the developer tools console and search for the access token, or if you prefer to right click on the page and select view source.
Mobile apps seem to be more secure at a first glance, because they are shipped as a binary, thus you would expect to be hard to reverse engineer it? Wrong, it's indeed easy with the plethora of open source tools that we can use to reverse engineer them, and my preference goes to the MobSF:
Mobile Security Framework (MobSF) is an automated, all-in-one mobile application (Android/iOS/Windows) pen-testing, malware analysis and security assessment framework capable of performing static and dynamic analysis.
So if you cannot find the access tokens via static analysis, then you can resort to dynamic analysis with open source tools to, like Frida:
Inject your own scripts into black box processes. Hook any function, spy on crypto APIs or trace private application code, no source code needed. Edit, hit save, and instantly see the results. All without compilation steps or program restarts.
And if that's is not enough you also perform a Man in the Middle(MitM) Attack wit another open source tools, like mitmproxy:
An interactive TLS-capable intercepting HTTP proxy for penetration testers and software developers.
So, stealing your access token for a mobile app is not as easy as in the Web App, but it's not that hard to.
POSSIBLE SOLUTIONS
How do we trust application and give it my access token?
I don't know if your application is a web or mobile app, therefore I will show you possible solutions for both.
Before I mention the possible solutions, I need to first clear out a usual misconception among developers, regarding who vs what is accessing the backend. This is discussed in detail in this article, where we can read:
The what is the thing making the request to the API server. Is it really a genuine instance of your mobile app, or is it a bot, an automated script or an attacker manually poking around your API server with a tool like Postman?
The who is the user of the mobile app that we can authenticate, authorize and identify in several ways, like using OpenID Connect or OAUTH2 flows.
If you still have doubts please go and read the section of the linked article, that also includes a graphic to help with understanding this. The article is in the context of a mobile app, but for understanding the difference between what and who is accessing the backend, the references to mobile app can be replaced with web app.
For Web Apps
If your use case is a web app the most affordable solution to try to mitigate the who vs what is accessing your backend it's by using:
Google Recaptcha V3:
reCAPTCHA is a free service that protects your site from spam and abuse. It uses advanced risk analysis techniques to tell humans and bots apart.
This is uses User Behaviour Analytics(UBA) in a best effort basis to tell appart who and what is accessing your backend.
User behavior analytics (UBA) as defined by Gartner is a cybersecurity process about detection of insider threats, targeted attacks, and financial fraud. UBA solutions look at patterns of human behavior, and then apply algorithms and statistical analysis to detect meaningful anomalies from those patterns—anomalies that indicate potential threats.[1] Instead of tracking devices or security events, UBA tracks a system's users.
This is prone to false positives, therefore you need to be careful when deciding to accept or not the request based on the score returned by reCPATCHA V3 for each request:
reCAPTCHA v3 returns a score for each request without user friction. The score is based on interactions with your site and enables you to take an appropriate action for your site.
For Mobile Apps
As you saw by the plethora of tools available to reverse engineer the mobile apps, statically or dynamically, the access token to identify your user is not that safe, plus this only identifies the who in the request, not what is doing it.
The solution that can let your backend to be sure that the request is indeed from the same exact mobile app that was uploaded to the Google Play or Apple store is a Mobile App Attestation solution, that is a concept that introduces a new way of dealing with security for your mobile app and backend in an unified manner.
The usual approaches focus to much on the mobile app side, but in first place the data you want to protect is in your backend server, and it's here that you want to have a way to know that what is making the request is really the thinh you expect to be, your genuine mobile app.
The Mobile App Attestation concept is described in this section of another article I wrote, from where I will quote the following text:
The role of a Mobile App Attestation service is to authenticate what is sending the requests, thus only responding to requests coming from genuine mobile app instances and rejecting all other requests from unauthorized sources.
In order to know what is sending the requests to the API server, a Mobile App Attestation service, at run-time, will identify with high confidence that your mobile app is present, has not been tampered/repackaged, is not running in a rooted device, has not been hooked into by an instrumentation framework (Frida, xPosed, Cydia, etc.) and is not the object of a Man in the Middle Attack (MitM). This is achieved by running an SDK in the background that will communicate with a service running in the cloud to attest the integrity of the mobile app and device it is running on.
On a successful attestation of the mobile app integrity, a short time lived JWT token is issued and signed with a secret that only the API server and the Mobile App Attestation service in the cloud know. In the case that attestation fails the JWT token is signed with an incorrect secret. Since the secret used by the Mobile App Attestation service is not known by the mobile app, it is not possible to reverse engineer it at run-time even when the app has been tampered with, is running in a rooted device or communicating over a connection that is the target of a MitM attack.
The mobile app must send the JWT token in the header of every API request. This allows the API server to only serve requests when it can verify that the JWT token was signed with the shared secret and that it has not expired. All other requests will be refused. In other words a valid JWT token tells the API server that what is making the request is the genuine mobile app uploaded to the Google or Apple store, while an invalid or missing JWT token means that what is making the request is not authorized to do so, because it may be a bot, a repackaged app or an attacker making a MitM attack.
So this approach will let your backend server to trust with a very high degree of confidence that the request is coming indeed from the same exact mobile app you uploaded to the Google Play and Apple store, provided the JWT token has a valid signature and expire time, and discard all other requests as untrustworthy ones.
GOING THE EXTRA MILE
To finish my answer I cannot resist to recommend you the excellent work of the OWASP foundation, because off their excellent work and for me no security solution for web and mobile is complete without going through their guides:
The Web Security Testing Guide:
The OWASP Web Security Testing Guide includes a "best practice" penetration testing framework which users can implement in their own organizations and a "low level" penetration testing guide that describes techniques for testing most common web application and web service security issues.
The Mobile Security Testing Guide:
The Mobile Security Testing Guide (MSTG) is a comprehensive manual for mobile app security development, testing and reverse engineering.

What is the accurate approach to achieve application authentication

Building a multi-tenant application. The tenancy of the application is organizations and each organization can have multiple projects.
As user authentication, implemented OAuth based authentication and role-based authorization.
Example
Let's assume our service serves images to the user applications and naming it imagebox server.
Now a user can register with our application. First, he needs to create an organization and then he can create multiple projects in an organization.
In a project, he can create an image with the following properties
Name of the image
Description
Upload an image ( It will automatically create a URL)
The customer on imagebox server, will create App Keys. Though we need only one app key per project. Though, he should be able to create multiple app keys as well delete the previous one whenever needed.
Now customer of our image box, download the SDK from the imagebox server. They write their application over the SDK and pass the APP key.
ImageBoxClient client = ImageBoxClientBuilder.build(APP_KEY);
The client should be able to access images of the project corresponding to the API key.
Questions
Is there any difference between API keys and App Keys?
How to handle Authorization - How to restrict only N:1 mapping between API key and project, a project can have multiple API keys but a key should belong to only one project?
How to achieve authorization in the above case (restrict key to the project), if I intended to use identity management solution like Azure AD?
How to achieve authorization in the above case (restrict key to the project), using API gateway?
Assumption
From your question its not clear if the client SDK's are mobile applications or not.
My answer will be based on the assumption that they are SDKs for mobile applications, but even doing so, a lot of what I will say it's still applicable for SDKs that aren't for mobile applications.
The Difference Between WHO and WHAT is Accessing the API Backend
As user authentication, implemented OAuth based authentication and role-based authorization.
User Authentication will identify WHO is accessing the API backend, but will not identify WHAT is accessing it on its behalf, and you are thinking in using an API key to identify the WHAT part.
So to better understand the differences between the WHO and the WHAT are accessing an API server, let’s use this picture:
The Intended Communication Channel represents the mobile app being used as you expected, by a legit user without any malicious intentions, using a genuine version of the mobile app, and communicating directly with the API backend without being man in the middle attacked.
The actual channel may represent several different scenarios, like a legit user with malicious intentions that may be using a repackaged version of the mobile app, a hacker using the genuine version of the mobile app, while man in the middle attacking it, to understand how the communication between the mobile app and the API backend is being done in order to be able to automate attacks against your API. Many other scenarios are possible, but we will not enumerate all possible ones here.
So the WHO is the user of the mobile app that we can authenticate, authorize and identify in several ways, like using OpenID Connect or OAUTH2 flows. The WHAT is the thing making the request to the API server. Is it really a genuine instance of the mobile app, or is a bot, an automated script or an attacker manually poking around with the API server, using a tool like Postman?
For your surprise you may end up discovering that the WHAT may be one of your legit users using a repackaged version of the mobile app or an automated script that is trying to gamify and take advantage of the service provided by the mobile application.
API Keys
For a project, there will be a unique app key using which SDK authenticate and identify the project.
So I think you want to say here that you will use an app-key or api-key header to identify WHAT client SDK is accessing the API backend in a per project basis, and this seems to be reinforced by:
Is the API key is the right solution, then how to restrict only N:1 mapping between API key and project, a project can have multiple API keys but a key should belong to only one project.
In my understanding the client SDK will need a specific API key per project, thus if it needs access to more then one project it will need to be released with one API key per project it needs access to.
While this may be useful to filter down and identify access to each project, I want to call your attention that it cannot be trusted as the only way to restrict access to them, and I hope that by now it's easy to see why, because you have already read about WHO vs WHAT is accessing the API backend? If not please go back and read about it.
Anything that its shipped into a client SDK must be considered public, and if you have shipped secrets with it, you need to considered that they are now compromised, because an SDK can be reverse engineered by de-compile it, or a MitM attacks can be performed to understand how it communicates with the backend, and instrumentation frameworks can be used during run-time to hook on the running code, and change its behavior, and/or extract data.
Extract an API key with Reverse Engineering
You can learn how to do it by reading my article How to Extract an API key from a Mobile App by Static Binary Analysis, and see how easy it can be done.
Using MobSF to reverse engineer an APK for a mobile app allows us to quickly extract an API key and also gives us a huge amount of information we can use to perform further analysis that may reveal more attack vectors into the mobile app and API server. It is not uncommon to also find secrets for accessing third part services among this info or in the decompiled source code that is available to download in smali and java formats.
The above article have a companion repository, that shows one of the most effective ways of hiding a secret in an mobile SDK, by using the JNI/NDK:
JNI is the Java Native Interface. It defines a way for the bytecode that Android compiles from managed code (written in the Java or Kotlin programming languages) to interact with native code (written in C/C++). JNI is vendor-neutral, has support for loading code from dynamic shared libraries, and while cumbersome at times is reasonably efficient.
Extract an API key with a MitM Attack
In the article Steal that API key with a Man in the Middle Attack I show an easier way to extract an API key, or any other secret, from a mobile app, and performing the MitM attack is made easy by using a tool like MiTM Proxy:
An interactive TLS-capable intercepting HTTP proxy for penetration testers and software developers.
Instrumentation Frameworks
A more advanced technique is to use instrumentation frameworks, like Frida or xPosed to hook into code at run-time, and change its behavior or extract the secrets from it.
Frida
Inject your own scripts into black box processes. Hook any function, spy on crypto APIs or trace private application code, no source code needed. Edit, hit save, and instantly see the results. All without compilation steps or program restarts.
xPosed
Xposed is a framework for modules that can change the behavior of the system and apps without touching any APKs. That's great because it means that modules can work for different versions and even ROMs without any changes (as long as the original code was not changed too much). It's also easy to undo.
So if your are storing secrets in the keys-tore of your device, an attacker just needs to poke around the code until he discovers the method that retrieves the secret from the vault, hook on it at runt-time and extract the secret without changing behavior, therefore staying under the radar. The extract secrets can then be sent to a remote control server, that will launch automated attacks against the API, just like if it was the WHO and the WHAT the API is expecting.
Defending an API Server
Depending on your budget and resources you may employ an array of different approaches and techniques to defend your API server, and I will start to enumerate some of the most usual ones, but before I do it so I would like to leave this note:
As a best practice a mobile app or a web app should only communicate with an API server that is under your control and any access to third party APIs services must be done by this same API server you control. This way you limit the attack surface to only one place, where you will employ as many layers of defense as what you are protecting is worth.
You can start with reCaptcha V3, followed by Web Application Firewall(WAF) and finally if you can afford it a User Behavior Analytics(UBA) solution.
Google reCAPTCHA V3:
reCAPTCHA is a free service that protects your website from spam and abuse. reCAPTCHA uses an advanced risk analysis engine and adaptive challenges to keep automated software from engaging in abusive activities on your site. It does this while letting your valid users pass through with ease.
...helps you detect abusive traffic on your website without any user friction. It returns a score based on the interactions with your website and provides you more flexibility to take appropriate actions.
WAF - Web Application Firewall:
A web application firewall (or WAF) filters, monitors, and blocks HTTP traffic to and from a web application. A WAF is differentiated from a regular firewall in that a WAF is able to filter the content of specific web applications while regular firewalls serve as a safety gate between servers. By inspecting HTTP traffic, it can prevent attacks stemming from web application security flaws, such as SQL injection, cross-site scripting (XSS), file inclusion, and security misconfigurations.
UBA - User Behavior Analytics:
User behavior analytics (UBA) as defined by Gartner is a cybersecurity process about detection of insider threats, targeted attacks, and financial fraud. UBA solutions look at patterns of human behavior, and then apply algorithms and statistical analysis to detect meaningful anomalies from those patterns—anomalies that indicate potential threats. Instead of tracking devices or security events, UBA tracks a system's users. Big data platforms like Apache Hadoop are increasing UBA functionality by allowing them to analyze petabytes worth of data to detect insider threats and advanced persistent threats.
All this solutions work based on a negative identification model, by other words they try their best to differentiate the bad from the good by identifying what is bad, not what is good, thus they are prone to false positives, despite of the advanced technology used by some of them, like machine learning and artificial intelligence.
So you may find yourself more often than not in having to relax how you block the access to the API server in order to not affect the good users. This also means that this solutions require constant monitoring to validate that the false positives are not blocking your legit users and that at same time they are properly keeping at bay the unauthorized ones.
Regarding APIs serving mobile apps a positive identification model can be used by using a Mobile App Attestation solution that allows the API server to verify with a very high degree of accuracy, that the requests are coming from WHO and WHAT is expected.
Conclusion
My recommendation is to use defense in depth, where you use as much techniques as you can afford and in accordance with the value of what you are trying to protect and the legal requirements for that type of data, like the GDPR regulations in Europe.The end goal is to increase the expertise and time necessary to overcome all defenses, to the point that the attacker may give up and move on to easier targets.
So defending an API server is a daunting task, and and never ended battle.

Storing api keys

I am using the Goodreads api to get book data for my react native app. I have to use a key for using the api. Is it OK for me to store the api key on the app itself or should I put the key on a server that redirects all the data to the app?
Is it OK for me to store the api key on the app itself
No, because as I demonstrate in the article How to Extract an API Key from a Mobile App by Static binary analysis it can be extracted with the help of several open source tools, like by using the Mobile Security Framework, but you can also grab the API key with a MitM attack, as I show in the article Steal that API Key with a Man in the Middle Attack, that uses the open source tool MiTM Proxy.
If you leave a third party API key in the mobile app, then they are up for grabs from attackers, and when they start using it without your knowledge your bill in the third party provider may go through the roof before you acknowledge that something is wrong, and on that time the only solution is to revoke the API key, thus shutting down the use of the mobile app, and if you make a new release of your mobile app with a new API key it will be just a matter of hours until the attacker come back and steal the API key again.
or should I put the key on a server that redirects all the data to the app?
Yes, and this is a good approach, because now you have only one place to store and protect all third part API keys. This have the benefit to let you control and throttle the use of them as you see fit.
With this solution you still need an API key in your mobile app to allow access to your API server, but while you continue vulnerable for attackers to steal it, you are now in direct control of throttling the access to your API server and if you identify in each access the WHO and the WHAT is accessing the API server, then you have a more fine grade control, but attacker will continue to be able to slip between all our defenses, because is very hard to know WHAT is accessing the API server.
You may be thinking by now... do you mind to explain the WHO vs the WHAT?
The Difference Between WHO and WHAT is Accessing the API Server
To better understand the differences between the WHO and the WHAT are accessing an API server, let’s use this picture:
The Intended Communication Channel represents the mobile app being used as you expected, by a legit user without any malicious intentions, using an untampered version of the mobile app, and communicating directly with the API server without being man in the middle attacked.
The actual channel may represent several different scenarios, like a legit user with malicious intentions that may be using a repackaged version of the mobile app, a hacker using the genuine version of the mobile app, while man in the middle attacking it, to understand how the communication between the mobile app and the API server is being done in order to be able to automate attacks against your API. Many other scenarios are possible, but we will not enumerate each one here.
I hope that by now you may already have a clue why the WHO and the WHAT are not the same, but if not it will become clear in a moment.
The WHO is the user of the mobile app that we can authenticate, authorize and identify in several ways, like using OpenID Connect or OAUTH2 flows.
OAUTH
Generally, OAuth provides to clients a "secure delegated access" to server resources on behalf of a resource owner. It specifies a process for resource owners to authorize third-party access to their server resources without sharing their credentials. Designed specifically to work with Hypertext Transfer Protocol (HTTP), OAuth essentially allows access tokens to be issued to third-party clients by an authorization server, with the approval of the resource owner. The third party then uses the access token to access the protected resources hosted by the resource server.
OpenID Connect
OpenID Connect 1.0 is a simple identity layer on top of the OAuth 2.0 protocol. It allows Clients to verify the identity of the End-User based on the authentication performed by an Authorization Server, as well as to obtain basic profile information about the End-User in an interoperable and REST-like manner.
While user authentication may let the API server know WHO is using the API, it cannot guarantee that the requests have originated from WHAT you expect, the original version of the mobile app.
Now we need a way to identify WHAT is calling the API server, and here things become more tricky than most developers may think. The WHAT is the thing making the request to the API server. Is it really a genuine instance of the mobile app, or is a bot, an automated script or an attacker manually poking around with the API server, using a tool like Postman?
For your surprise you may end up discovering that It can be one of the legit users using a repackaged version of the mobile app or an automated script that is trying to gamify and take advantage of the service provided by the application.
Well, to identify the WHAT, developers tend to resort to an API key that usually they hard-code in the code of their mobile app. Some developers go the extra mile and compute the key at run-time in the mobile app, thus it becomes a runtime secret as opposed to the former approach when a static secret is embedded in the code.
The above write-up was extracted from an article I wrote, entitled WHY DOES YOUR MOBILE APP NEED AN API KEY?, and that you can read in full here, that is the first article in a series of articles about API keys.
Your problem is not solved yet
Now that you know the difference between WHO and WHAT is accessing your API server you must have realized that your API server is still vulnerable to be abused by attackers.
You can resort now to employ several layers of defense, starting with reCaptcha V3, followed by Web Application Firewall(WAF) and finally if you can afford it a User Behavior Analytics(UBA) solution.
Google reCAPTCHA V3:
reCAPTCHA is a free service that protects your website from spam and abuse. reCAPTCHA uses an advanced risk analysis engine and adaptive challenges to keep automated software from engaging in abusive activities on your site. It does this while letting your valid users pass through with ease.
...helps you detect abusive traffic on your website without any user friction. It returns a score based on the interactions with your website and provides you more flexibility to take appropriate actions.
WAF - Web Application Firewall:
A web application firewall (or WAF) filters, monitors, and blocks HTTP traffic to and from a web application. A WAF is differentiated from a regular firewall in that a WAF is able to filter the content of specific web applications while regular firewalls serve as a safety gate between servers. By inspecting HTTP traffic, it can prevent attacks stemming from web application security flaws, such as SQL injection, cross-site scripting (XSS), file inclusion, and security misconfigurations.
UBA - User Behavior Analytics:
User behavior analytics (UBA) as defined by Gartner is a cybersecurity process about detection of insider threats, targeted attacks, and financial fraud. UBA solutions look at patterns of human behavior, and then apply algorithms and statistical analysis to detect meaningful anomalies from those patterns—anomalies that indicate potential threats. Instead of tracking devices or security events, UBA tracks a system's users. Big data platforms like Apache Hadoop are increasing UBA functionality by allowing them to analyze petabytes worth of data to detect insider threats and advanced persistent threats.
All this solutions work based on a negative identification model, by other words they try their best to differentiate the bad from the good by identifying what is bad, not what is good, thus they are prone to false positives, despite of the advanced technology used by some of them, like machine learning and artificial intelligence.
So you may find yourself more often than not in having to relax how you block the access to the API server in order to not affect the good users. This also means that this solutions require constant monitoring to validate that the false positives are not blocking your legit users and that at same time they are properly keeping at bay the unauthorized ones.
Regarding APIs serving mobile apps a positive identification model can be used by using a Mobile App Attestation solution that guarantees to the API server that the requests can be trusted without the possibility of false positives.
Mobile App Attestation
Use a Mobile App Attestation solution to enable the API server to know is receiving only requests from a genuine mobile app.
The role of a Mobile App Attestation service is to guarantee at run-time that your mobile app was not tampered or is not running in a rooted device by running a SDK in the background that will communicate with a service running in the cloud to attest the integrity of the mobile app and device is running on.
On successful attestation of the mobile app integrity a short time lived JWT token is issued and signed with a secret that only the API server and the Mobile App Attestation service in the cloud are aware. In the case of failure on the mobile app attestation the JWT token is signed with a secret that the API server does not know.
Now the App must sent with every API call the JWT token in the headers of the request. This will allow the API server to only serve requests when it can verify the signature and expiration time in the JWT token and refuse them when it fails the verification.
Once the secret used by the Mobile App Attestation service is not known by the mobile app, is not possible to reverse engineer it at run-time even when the App is tampered, running in a rooted device or communicating over a connection that is being the target of a Man in the Middle Attack.
The Mobile App Attestation service already exists as a SAAS solution at Approov(I work here) that provides SDKs for several platforms, including iOS, Android, React Native and others. The integration will also need a small check in the API server code to verify the JWT token issued by the cloud service. This check is necessary for the API server to be able to decide what requests to serve and what ones to deny.
Summary
Anything that runs on the client side and needs some secret to access an API can be abused in different ways and you must delegate the access to all third part APIs to a backend under your control, so that you reduce the attack surface, and at the same time protect their secrets from public pry eyes.
In the end, the solution to use in order to protect your API server must be chosen in accordance with the value of what you are trying to protect and the legal requirements for that type of data, like the GDPR regulations in Europe.
For react native use react-native-config library. While using this library you can secure your api keys as well as you can save more secret keys which use in the native code. Like we can save onesignal, codepush etc keys.
https://github.com/luggit/react-native-config
Store them in a .env file like this API_KEY=yourKey.
Install npm package react-native-dotenv.
Then import to to files as needed with react-native-dotenv package;
import { API_KEY } from 'react-native-dotenv'
The .env file should never be committed to Github.

How to protect secrets properly?

I am using HERE api in both frontend and backend. If I try to put my app_id and app_code into the frontend code, it will be available to anyone seeing my site.
I can try to create a domain whitelist and put my domain in this. But still, if I set the HTTP header "Referer" to my domain, I am able to access the API from any IP.
So, what do I do?
The Difference Between WHO and WHAT is Accessing the API Server
Before I dive into your problem I would like to first clear a misconception about WHO and WHAT is accessing an API server.
To better understand the differences between the WHO and the WHAT are accessing an API server, let’s use this picture:
So replace the mobile app by web app, and keep following my analogy around this picture.
The Intended Communication Channel represents the web app being used as you expected, by a legit user without any malicious intentions, communicating with the API server from the browser, not using Postman or using any other tool to perform a man in the middle(MitM) attack.
The actual channel may represent several different scenarios, like a legit user with malicious intentions that may be using Curl or a tool like Postman to perform the requests, a hacker using a MitM attack tool, like MitmProxy, to understand how the communication between the web app and the API server is being done in order to be able to replay the requests or even automate attacks against the API server. Many other scenarios are possible, but we will not enumerate each one here.
I hope that by now you may already have a clue why the WHO and the WHAT are not the same, but if not it will become clear in a moment.
The WHO is the user of the web app that we can authenticate, authorize and identify in several ways, like using OpenID Connect or OAUTH2 flows.
OAUTH
Generally, OAuth provides to clients a "secure delegated access" to server resources on behalf of a resource owner. It specifies a process for resource owners to authorize third-party access to their server resources without sharing their credentials. Designed specifically to work with Hypertext Transfer Protocol (HTTP), OAuth essentially allows access tokens to be issued to third-party clients by an authorization server, with the approval of the resource owner. The third party then uses the access token to access the protected resources hosted by the resource server.
OpenID Connect
OpenID Connect 1.0 is a simple identity layer on top of the OAuth 2.0 protocol. It allows Clients to verify the identity of the End-User based on the authentication performed by an Authorization Server, as well as to obtain basic profile information about the End-User in an interoperable and REST-like manner.
While user authentication may let the API server know WHO is using the API, it cannot guarantee that the requests have originated from WHAT you expect, the browser were your web app should be running from, with a real user.
Now we need a way to identify WHAT is calling the API server, and here things become more tricky than most developers may think. The WHAT is the thing making the request to the API server. Is it really a genuine instance of the web app, or is a bot, an automated script or an attacker manually poking around with the API server, using a tool like Postman?
For your surprise, you may end up discovering that It can be one of the legit users manipulating manually the requests or an automated script that is trying to gamify and take advantage of the service provided by the web app.
Well, to identify the WHAT, developers tend to resort to an API key that usually is sent in the headers of the web app. Some developers go the extra mile and compute the key at run-time in the web app, inside obfuscated javascript, thus it becomes a runtime secret, that can be reverse engineered by deobusfaction tools, and by inspecting the traffic between the web app and API server with the F12 or MitM tools.
The above write-up was extracted from an article I wrote, entitled WHY DOES YOUR MOBILE APP NEED AN API KEY?. While in the context of a Mobile App, the overall idea is still valid in the context of a web app. You wish you can read the article in full here, that is the first article in a series of articles about API keys.
Your Problem
I can try to create a domain whitelist and put my domain in this. But still, if I set the HTTP header "Referer" to my domain, I am able to access the API from any IP.
So this seems to be related with using the HERE admin interface, and I cannot help you here...
So, what do I do?
I am using HERE API in both frontend and backend.
The frontend MUST always delegate access to third part APIs into a backend that is under the control of the owner of the frontend, this way you don't expose access credentials to access this third part services in your frontend.
So the difference is that now is under your direct control how you will protect against abuse of HERE API access, because you are no longer exposing to the public the HERE api_id and api_code, and access to it must be processed through your backend, where your access secrets are hidden from public pry eyes, and where you can easily monitor and throttle usage, before your bill skyrockets in the HERE API.
If I try to put my app_id and app_code into the frontend code, it will be available to anyone seeing my site.
So to recap, the only credentials you SHOULD expose in your frontend is the ones to access your backend, the usual api-key and Authorization tokens, or whatsoever you want to name them, not the api_id or api_code to access the HERE API. This approach leaves you only with one access to protect, instead of multiple ones.
Defending an API Server
As I already said, but want to reinforce a web app should only communicate with an API server that is under your control and any access to third part APIs services must be done by this same API server you control. This way you limit the attack surface to only one place, where you will employ as many layers of defence as what you are protecting is worth.
For an API serving a web app, you can employ several layers of dense, starting with reCaptcha V3, followed by Web Application Firewall(WAF) and finally if you can afford it a User Behavior Analytics(UBA) solution.
Google reCAPTCHA V3:
reCAPTCHA is a free service that protects your website from spam and abuse. reCAPTCHA uses an advanced risk analysis engine and adaptive challenges to keep automated software from engaging in abusive activities on your site. It does this while letting your valid users pass through with ease.
...helps you detect abusive traffic on your website without any user friction. It returns a score based on the interactions with your website and provides you more flexibility to take appropriate actions.
WAF - Web Application Firewall:
A web application firewall (or WAF) filters, monitors, and blocks HTTP traffic to and from a web application. A WAF is differentiated from a regular firewall in that a WAF is able to filter the content of specific web applications while regular firewalls serve as a safety gate between servers. By inspecting HTTP traffic, it can prevent attacks stemming from web application security flaws, such as SQL injection, cross-site scripting (XSS), file inclusion, and security misconfigurations.
UBA - User Behavior Analytics:
User behavior analytics (UBA) as defined by Gartner is a cybersecurity process about the detection of insider threats, targeted attacks, and financial fraud. UBA solutions look at patterns of human behavior, and then apply algorithms and statistical analysis to detect meaningful anomalies from those patterns—anomalies that indicate potential threats. Instead of tracking devices or security events, UBA tracks a system's users. Big data platforms like Apache Hadoop are increasing UBA functionality by allowing them to analyze petabytes worth of data to detect insider threats and advanced persistent threats.
All these solutions work based on a negative identification model, by other words they try their best to differentiate the bad from the good by identifying what is bad, not what is good, thus they are prone to false positives, despite the advanced technology used by some of them, like machine learning and artificial intelligence.
So you may find yourself more often than not in having to relax how you block the access to the API server in order to not affect the good users. This also means that these solutions require constant monitoring to validate that the false positives are not blocking your legit users and that at the same time they are properly keeping at bay the unauthorized ones.
Summary
Anything that runs on the client side and needs some secret to access an API can be abused in different ways and you must delegate the access to all third part APIs to a backend under your control, so that you reduce the attack surface, and at the same time protect their secrets from public pry eyes.
In the end, the solution to use in order to protect your API server must be chosen in accordance with the value of what you are trying to protect and the legal requirements for that type of data, like the GDPR regulations in Europe.
So using API keys may sound like locking the door of your home and leave the key under the mat, but not using them is liking leaving your car parked with the door closed, but the key in the ignition.
Going the Extra Mile
OWASP Web Top 10 Risks
The OWASP Top 10 is a powerful awareness document for web application security. It represents a broad consensus about the most critical security risks to web applications. Project members include a variety of security experts from around the world who have shared their expertise to produce this list.