Securing API key from reverse engineer in a React-Native app - react-native

I recently read a lot of post and article about securing sensitive info into a React Native app. From what I understand, you can't fully protect your sensitive info but only make hacker's life harder to get them.
So, from that point of view, I would like to know if it wouldn't be "safer" to get those sensitive info (i.e. API keys) from an external server (i.e. Rest API).
I explain:
I know about MitM attacks, but would it be safer (and more flexible) to have my mobile app calling my API to get API keys on request thru HTTPS? This way, no sensitive info remains in the app binary files.
And to secure MitM attacks, I could frequently change those API key values so they would remains valid only on a short period of time.
I would like to hear anyone about PROS and CONS of such a system.

APIs Misconceptions
To prepare you for my answer I will first clear out some usual misconceptions around public/private APIs and about who vs what is really accessing your backend.
Public and Private APIs
I often see that developers think that their APIs are private, because they have no docs for it, have not advertise it anywhere, and many other reasons.
The truth is that when you release a mobile app all the APIs it communicates with are now belonging to the public domain and if this APIs don't have an authentication and authorization mechanism in place then all data behind it can be accessed by anyone in the internet that reverse engineers how your mobile app works. Even when APIs have authentication in place they may be vulnerable to bad implementations of it and some have a total lack of authorization mechanisms or buggy ones as per OWASP API Security Top 10 vulnerability list.
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 detail the difference between who and what is accessing your API server, but I will extract here the main takes 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.
API Keys Service
I know about MitM attacks, but would it be safer (and more flexible) to have my mobile app calling my API to get API keys on request thru HTTPS? This way, no sensitive info remains in the app binary files.
While you indeed don't have any sensitive info in the app binary files you haven't solved the problem. In my opinion you are more exposed, because you are now getting the API keys from an public and open API endpoint.
I say it's open because you don't have any safeguard that what is making the request to it are indeed a genuine and untampered version of your mobile app.
So, now all an attacker needs to do is to MitM attack your mobile app or decompile it to see from which API endpoint you grab the API keys to make the requests, and then replicate the procedure from their automated scripts/bots, therefore doesn't really matter that you don't have them hardcoded in the app binary any more.
API Keys Rotation
And to secure MitM attacks, I could frequently change those API key values so they would remains valid only on a short period of time.
In light of the above explanation , on the API Keys Service section, you can even make the API keys restricted to be used only for one single request that the attacker will still succeed, because the attacker will be able to query the API endpoint to obtain API keys as if he was what the backend expects, a genuine and untampered version of your mobile app.
So, to be clear I am in favour of API keys rotation but only if you can get them into your mobile app from a secured external source, but your approach is open to be accessed by anyone on the internet.
I would like to hear anyone about PROS and CONS of such a system.
The system you are describing is not advisable to implement, because without being secured it's just a security disaster asking to occur. Securing it with an API key it's just going back to the initial problem with the disadvantage that your giving back to the mobile the sensitive info you want to keep away from hackers.
The best approach for you is to use a Reverse Proxy to keep the API keys private and secured from prying eyes.
The Reverse Proxy Approach
So, from that point of view, I would like to know if it wouldn't be "safer" to get those sensitive info (i.e. API keys) from an external server (i.e. Rest API).
What you are looking for is to implement a Reverse Proxy, that is usually used to protect access to third party APIs and your own APIs, by having the mobile app delegating the API requests to the Reverse Proxy, instead of asking for the API keys to make them from inside the mobile app.
The Reverse Proxy approach will avoid to have several API keys harcoded in the mobile app, but you still need one API key to protect access to the Reverse Proxy, therefore you are still vulnerable to the MitM attacks and to static reverse engineering of your mobile app.
The advantage now is that all your sensitive API keys are private and in an environment you can control and employ as many security measures you need to ensure that the request are indeed from what your backend expects, a genuine and untampered version of your mobile app.
Learn more about using a Reverse Proxy by reading the article I wrote Using a Reverse Proxy to Protect Third Party APIs:
In this article you will start by learning what Third Party APIs are, and why you shouldn’t access them directly from within your mobile app. Next you will learn what a Reverse Proxy is, followed by when and why you should use it to protect the access to the Third Party APIs used in your mobile app.
While the article focus on third party APIs the principle also applies to use with your own APIs.
Preventing MitM Attacks
When certificate pinning is implemented in a mobile app to secure the https channel then the sensitive data on the API requests is more safeguarded from being extracted.
I recommend you to read the section Preventing MitM Attacks in this answer I gave to another question where you will learn how to implement static certificate pinning and how to bypass it.
Despite being possible to bypass certificate pinning I still strongly recommend it to be implemented, because it reduces the attack surface on your mobile app.
A Possible Better Solution
I recommend you to read this answer I gave to the question How to secure an API REST for mobile app?, especially the sections Hardening and Shielding the Mobile App, Securing the API Server and A Possible Better Solution.
The solution will be the use of a Mobile App Attestation solution that will allow your backend to have an high degree of confidence that the request is from what it expects, a genuine and untampered version of your mobile app.
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 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.
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.

Related

React Native security concerns with data exchange to api

We want to write an react native app that:
-gets data over bluetooth from devices
-the app should send the data to our api
-it's important that the data is not tempered with or changed in any way
-the app is the only one that can send data to our api
I already read a lot about:
iOS - Keychain Services and
Android - Keystore
on the React Native docs: https://reactnative.dev/docs/security
And SafeNet(Android) or DevieCheck(IOS) (never mentioned on react native docs or articles I read)
What security layers should we use for our use case to make the api most secure and how can I implement them in react native?
We want to use the data from the api to verify the correctness of the same data passed to a smart contract that compares and evaluates them.
YOUR PROBLEM
We want to use the data from the api to verify the correctness of the same data passed to a smart contract that compares and evaluates them.
I congratulate you by having taken the time to understand that the API sitting in front of a blockchain needs to be protected against abuse in order to prevent the blockchain from ingesting unwanted data.
Defending an API it's not an easy task, but if you read carefully all I am about to say I hope that by the end you will have a new perspective on API and Mobile security, that will allow you to devise and architect a robust and secure solution.
WHO IS IN THE REQUEST VERSUS WHAT IS MAKING THE REQUEST
-the app is the only one that can send data to our api
This is a very hard problem to solve, but not an impossible one. To understand why you need to first know the difference between who is in the request and what is making it, otherwise any security you add may not be protecting your API as expected.
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 detail the difference between who and what is accessing your API server, but I will extract here the main takes 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.
DATA INTEGRITY
-gets data over bluetooth from devices
-the app should send the data to our api
-it's important that the data is not tempered with or changed in any way
This is also very hard to solve. During the process of collecting the data and sending it to the API the data can be tampered with in several ways.
Manipulate Data with an Instrumentation Framework
-gets data over bluetooth from devices
While the data is being collected form the devices an instrumentation framework can be used to manipulate the data before sending it to the API. A popular instrumentation framework is 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.
So, the attacker would inject a script to listen at runtime to the method that collects the data or to the one that sends the data to the API and then tamper with the data its being sent.
the app should send the data to our api
Manipulating Data with a MitM Attack
Another alternative is for the attacker to also use Frida to perform a MitM attack to allow a tool like mitmproxy to intercept and modify the request. You can learn how to perform a MitM attack with Frida by reading my article How to Bypass Certificate Pinning with Frida on an Android App:
Today I will show how to use the Frida instrumentation framework to hook into the mobile app at runtime and instrument the code in order to perform a successful MitM attack even when the mobile app has implemented certificate pinning.
Bypassing certificate pinning is not too hard, just a little laborious, and allows an attacker to understand in detail how a mobile app communicates with its API, and then use that same knowledge to automate attacks or build other services around it.
The injection of Frida scripts at runtime allows for almost unlimited possibilities in how to tamper with your data integrity or whatever the mobile app is doing at runtime.
POSSIBLE SOLUTIONS
Secure Storage
I already read a lot about:
iOS - Keychain Services and
Android - Keystore
on the React Native docs: https://reactnative.dev/docs/security
Using this mechanism is recommended, but you need to be aware that anything that is stored in secure storage will need to be accessed and used by the mobile app at some point, and this is when the attacker can use an instrumentation framework to hook at runtime into the mobile app code. For example, when retrieving a securely stored secret the attacker can extract it to use outside of the mobile app to automate API requests as if they were from the mobile app.
So, use it to make it harder for less skilled attackers to tamper with your mobile app, but always remember that more skilled attackers may find their way around it.
Protecting Data Integrity in the Mobile App
-it's important that the data is not tempered with or changed in any way
To protecting data from being tampered with before it arrives to the API server it's necessary that you employ some solutions, like RASP:
Runtime application self-protection (RASP) is a security technology that uses runtime instrumentation to detect and block computer attacks by taking advantage of information from inside the running software.
RASP technology is said to improve the security of software by monitoring its inputs, and blocking those that could allow attacks, while protecting the runtime environment from unwanted changes and tampering.
The issue of using only RASP is that the API server doesn't have visibility for the ongoing attacks on the mobile app, therefore not able to refuse requests from a mobile app under attack. Also, RASP can be bypassed by skilled attackers with the use of instrumentations frameworks, and the API server will not be aware of this happening, therefore will continue to serve requests, because it doesn't have a mechanism to know that what is making the request is indeed a genuine and un-tampered version of your mobile app.
Defending the API Server
I recommend you to read this answer I gave to the question How to secure an API REST for mobile app?, especially the sections Hardening and Shielding the Mobile App, Securing the API Server and A Possible Better Solution.
One of the solutions proposed is to use a Mobile App Attestation solution that runs outside the mobile device, for example on the cloud, therefore doesn't make client side decisions about the state of the mobile app and device is running on, instead they are done in the cloud service and transmitted to the API server as signed JWT token, that the API server can then used to verify that what is making the request is indeed the genuine and un-tampered version of the official mobile app.
Android Safetynet and iOS Devicecheck
And SafeNet(Android) or DevieCheck(IOS) (never mentioned on react native docs or articles I read)
Using the Android SafetyNet and iOS DeviceCheck runtime protections is for sure a good starting point, but you need to be aware of their scope, limitations and complexity. They can be complemented with a robust Mobile App Attestation solution to give you an higher level of security and confidence that your API server will be able to know when the request is not from what it expects, a genuine and un-tampered version of your mobile app.
Security Layers
What security layers should we use for our use case to make the api most secure and how can I implement them in react native?
I would not be approaching here how to implement it in React, because that is a huge topic and the exact code will depend on your current implementation, but I will summarize here the key points.
Security is always about adding as many layers as you can afford and are required by law, standards and business requirements. To summarize you should consider the following topics:
Don't hardcode secrets in your mobile app code, but if you really want to do it, at least use Native C code.
Obfuscate your mobile app code, because this will make it harder to reverse engineer the mobile app code in order to use instrumentations frameworks.
Use runtime protections in your mobile app code and give preference to the ones that don't make decisions on the client side and allow for the API server to verify that the request is indeed from what it expects, a genuine and un-tampered version of your mobile app, like describe in the Mobile App Attestation I mentioned previously.
Use certificate pinning to the public key to prevent MitM attacks, but wit h the awareness that it can be bypassed. I recommend you to read the section Preventing MitM Attacks in this answer I gave to another question where you will learn how to implement static certificate pinning. If you can, try to use instead dynamic certificate pinning to allow to remotely update the pins used by your mobile app.
In your API server you can use rate limiting but do not give back in the headers the info about the rate limit available, because that is like putting the key to your front door under the mat.
You can use Artificial Intelligence solutions, but be aware that they work in a negative identification model and are prone to false negatives and positives. If using a mobile app runtime protection that lets the API server know when is under attack then the use of AI solutions can be postponed until the API server needs to use other type of clients, like web apps.
This is not an exclusive list of topics you can consider to use in order to secure your mobile app and API server, but are the ones I think that more important for you to focus on.
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 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.
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.

How do you secure project-wide API keys in a mobile app [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed last month.
Improve this question
Numerous other questions on S.E ask exactly this same question.
Some of the highest rated questions are closed as Opinion Based, eg Best practice for storing and protecting private API keys in applications
Some best practices are published here:
https://support.google.com/googleapi/answer/6310037?hl=en
In summary:
Do not embed API keys directly in code
Do not store API keys in files inside your application's source tree
Restrict your API keys to be used by only the IP addresses, referrer URLs, and mobile
apps that need them
(This is not possible if you do not know where the client running on a mobile app will be connecting from using the keys)
Restrict your API keys to be usable only for certain APIs
(When you are not the creator of the API this is not possible)
Delete unneeded API keys
Regenerate your API keys periodically
(Nr 5 and 6 is also not practical for Mobile applications, unless you force the user to Update the app every few days.)
If we pay attention to those best practices it gives Don't but no clear Do's for Mobile apps that need access to, for example, a stock trading API.
Relying on obfuscation such as ProGuard or DexGuard does not void #1 or #2 above, so how does one solve this issue?
TL/DR: You don't.
Long answer:
Any key that is distributed with the app can be read by the app for it to use it. The app therefore has what it needs to read the key, even if it is encrypted or obfuscated. An attacker can use the same technique that the app would use, to obtain the key.
Equally, fetching the key form an external source does not protect it. Again an attacker can use the same channel to obtain a copy of the key.
Besides attacking the channel by which the app obtains the key (from an encrypted store inside the package, or from an external source), an attacker can also obtain it from the app's memory or by intercepting network transmissions.
The only secure solution is to never have a copy of the key on the end user device.
The key should be kept on a well secured server which will act as a middle-man between the user's device and the end service. Any requests by the client device to the end service needs to be routed via this server.
The server, having the "global project keys", should make the requests to the end service on the behalf of the end user, and return the result (and never any keys) to the client. For the client to use this server, a per-user authenticated session must be used. The server must validate this session for every request prior to forwarding the request on to the end service.
Summary:
Use a secure server between the client and the end service to make requests on behalf of clients using the global key.
EDIT:
Side note: There is a distinction that needs to be made between per-user keys and keys that are project-wide. It is acceptable to keep keys that are specific to one individual person on that user's device.
Hide that API Key
Relying on obfuscation such as ProGuard or DexGuard does not void #1 or #2 above, so how does one solve this issue?
While ProGuard or DexGuard don't solve the issue they will make it harder, by renaming the name that the API keys is associated with, while if the API key is hidden in native C code the string of it will not be associated with any reference when performing static binary analysis, therefore making it more difficult to extract as I show in my article How to Extract an API key from a Mobile App with Static Binary Analysis:
The range of open source tools available for reverse engineering is huge, and we really can't scratch the surface of this topic in this article, but instead we will focus in using the Mobile Security Framework(MobSF) to demonstrate how to reverse engineer the APK of our mobile app. MobSF is a collection of open source tools that present their results in an attractive dashboard, but the same tools used under the hood within MobSF and elsewhere can be used individually to achieve the same results.
During this article we will use the Android Hide Secrets research repository that is a dummy mobile app with API keys hidden using several different techniques.
While this solution makes it very difficult to extract the API key with binary analysis, doesn't make it impossible, but easier approaches exist to extract the API key, like by doing a MitM attack as I demo in my article Steal that Api Key with a Man in the Middle Attack:
In order to help to demonstrate how to steal an API key, I have built and released in Github the Currency Converter Demo app for Android, which uses the same JNI/NDK technique we used in the earlier Android Hide Secrets app to hide the API key.
So, in this article you will learn how to setup and run a MitM attack to intercept https traffic in a mobile device under your control, so that you can steal the API key. Finally, you will see at a high level how MitM attacks can be mitigated.
An instrumentation Framework can also be used in conjunction with the MitM attack to bypass certificate pinning when the mobile app is using it. A popular one is 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.
Reverse Proxy Server
If we pay attention to those best practices it gives Don't but no clear Do's for Mobile apps that need access to, for example, a stock trading API.
Another common approach to solve the issue of storing API keys in the mobile app code is to delegate the responsibility for accessing Third Party APIs to a Reverse Proxy like I wrote in the article
Using a Reverse Proxy to Protect Third Party APIs:
In this article you will start by learning what Third Party APIs are, and why you shouldn’t access them directly from within your mobile app. Next you will learn what a Reverse Proxy is, followed by when and why you should use it to protect the access to the Third Party APIs used in your mobile app.
Now, this only shifts the issue from protecting the API key for the third party service, like the stock trading API, to protect the API key or any other secret/identifier used to access the Reverse Proxy, but with the advantage that you now have control of how the third party API can be accessed, while keeping the API key to access it out of reach of the mobile app attacker.
Using user authentication to protect access to the Reverse Proxy will limit the scope of the attack, but will not eliminate it, because the Reverse Proxy server needs to be able to distinguish the who from what is doing the request, and in my experience I have seen that developers of any seniority are not often aware of this difference or have a misconception about it.
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 detail the difference between who and what is accessing your backend, be it an API server or a Reverse Proxy server. I will extract here the main takes aways 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 the Reverse Proxy server will be able to Authenticate and Authorize access to the third party service(stock trading API in your example), and think about the what as the software making that request in behalf of the user.
Hardening the Reverse Proxy Server
If we pay attention to those best practices it gives Don't but no clear Do's for Mobile apps that need access to, for example, a stock trading API.
The Reverse Proxy server can be equipped with User Behavior Analytics(UBA) solutions to give it the ability to distinguish from who vs what is doing the request, but this will be done in a best effort basis, based on historical data used by the Artificial Intelligence algorithm to score the probability of being a human or not doing the request, aka the who.
While UBA solutions will reduce significantly the attack surface, it's still a negative identification model, due to the occurrence of false negatives and positives, and will require constant monitoring of the policies/rules being used by the algorithm to strike the best balance between not blocking too many legit users and not letting too many attacks pass by.
A positive identification model can be used instead, by employing the Mobile App Attestation concept as I recommend in this answer I gave to the question How to secure an API REST for mobile app?, on the section A Possible Better Solution.
So, the Mobile App Attestion in a nutshell can be described as a solution that will be able to lock-down, with a very high degree of confidence, the Reverse Proxy server with the mobile app, because the Reverse Proxy server will now be able to only accept requests from what it expects, aka genuine and untampered versions of the mobile app.
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 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.
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.

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.

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.

Need to generate API key for different application

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.