I am developing Android Translation App. The app uses Azure cognitive service text translation API key.
The API key is inside the App source code in Java file, and if I publish the app, people can crack the app apk file and use my API key, which will be quite expensive. Is there away how to protect my API key from being stolen? There is no login in the app, no sign in and anyone can download it from play store.
How can I protect the API key from being stolen?
You can use android Keystore which is there for a scenario like yours official docs
or can refer to a sample code here
Reverse Engineering
The API key is inside the App source code in Java file, and if I publish the app, people can crack the app apk file and use my API key
Yes, and its not hard to do when a lot of different open-sources exist to make this task easy to achieve, even by non technical people, like I demo with the Mobile Security Framework 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.
Also, you can use the grep command in the upload directory of MobSF to find other secrets that MobSF is not able to find:
grep -irl '_key"' --include 'strings.xml' --include "AndroidManifest.xml"
and
grep -irn '_key' --include '*.java' --include "*.smali" ./java_source/tld/domain ./smali_source/tld/domain
Replace _key with whatever other pattern you may want to look for.
Replace tld/domain with the one used by the mobile app being reverse engineered, e.g: com/example.
Secret Hidden in Native C Code
Secrets can be hidden in native C code as in the demo on the above linked article:
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.
But then if you cannot find it with static analysis then you do a MitM attack, as I demo on this other 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.
Secrets in Hardware Keystores or Vaults
An alternative to the MitM attack is to use an instrumentation framework to hook at runtime to the code that retrieves the secret, be it from the Android Hardware baked Keystore or from any other vault provided by your cloud provider of choice:
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.
Third Party Services
The API key is inside the App source code in Java file, and if I publish the app, people can crack the app apk file and use my API key, which will be quite expensive.
Yes, it can be very expensive and you only discover it when the bill is already huge, despite you can set billing alerts, they don't work as you may think they do.
Reverse Proxy to the Rescue
Is there away how to protect my API key from being stolen?
Best practices don't recommend to use third party services directly from within a mobile app, instead they should be delegated to the API backend for the mobile app or to a Reverse Proxy, as I wrote in this my other 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.
So, by now you may think that you are just shifting from protecting the secret for accessing the translation API for the one to access the Reverse Proxy or API backend, and you are right, but with a huge difference, that makes all the difference, you are in control of the Reverse Proxy and/or API backend, therefore you can closely monitor the traffic, throtle/shutdown it and apply as many security defenses as necessary to keep things under control.
Open APIs
There is no login in the app, no sign in and anyone can download it from play store.
So, you have created a friction-less user experience but you have also created a security nightmare for yourself to solve.
Before I delve in more details it's important to first clarify some misconception around the difference between who vs what is accessing the backend.
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.
You can think about the who as the user your API backend or Reverse Proxy could be able to Authenticate and Authorize access to the data(if you were using it), and think about the what as the software making that request in behalf of the user.
In an open API you are not able to identify the who in the request, but even if you were able it would not be enough to lock-down the mobile app with the API backend or Reverse Proxy.
So, what you need to strength the delegation of the third party service to your own backend or reverse proxy is to find a way of locking them down with the mobile app.
A Possible Additional Solution
Is there away how to protect my API key from being stolen?
The mobile app and the API backend and/or Reverse Proxy can be tight together by locking them down in a way that they only accept requests comming from a genuine and untampered version of your mobile app by introducing the Mobile App Attestation concept, and 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 to learn some more defense techniques and to learn about Mobile App Attestation.
In a nutshell the Mobile App Attestation solution will allow for any backend to assert with a very high degree of confidence that the request comes indeed from what you expect, a genuine and untampered version of your mobile app, aka not from a bot, script, cURL or any other tool.
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.
Another way to make your keys hard to reverse engineer is to save them in the NDK as native code.
One more solution is to create you own service proxy, which is your REST service that takes user requests, gets translation responses from AWS, and sends back responses to mobile devices.
The beauty is the secret key won't be stored on the mobile device while the downside is that your REST service becomes the single point of failure therefore you may need to provision redundant servers.
However, as your service is light-weighted, it shall scale well.
Related
Is it possible for other apps to read my app's signature toString() format? Because I'm using my app's signature as the first core security of my app. Is it possible to crack? What else can i use as a password of my app that can't be seen even when decompiled? That my app will get void when that thing has changed or my app gets decompiled?
Your Mobile App APK is Public: You Don't Control It Any-more
Is it possible for other apps to read my app's signature toString() format?
From the moment you ship your mobile app to the public you loose the control of it and anything on it it's not a secret any more because a lot of open source tools exist to help reverse engineer it easily, for example 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.
Instrumentations frameworks are also often used by attackers to perform dynamic analysis at runtime, for example 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.
If your mobile app relies only on its own signature to prevent modifications to it at runtime then it will fail to be effective to defend against attackers, but may prevent abuse from script kids. All an attacker needs to do is to statically reverse engineer your mobile app, find and remove the protections you put in place, repackage it and sign the app with it's own key.
Repackaging mobile apps and offer them in the official Google Play store or other alternative stores is more common then lots of developers may think, and a well known one that made the news was Pokémon Go:
Remember Pokémon Go, the location-based augmented reality mobile game from Niantic Labs that became an overnight global sensation when it launched in 2016? Well, the game has had a record 2019 having surpassed its launch year in revenues, announced a live AR multiplayer feature, and, on a slightly dissonant note, sued an “association of hackers” for creating and distributing unauthorized derivative versions of the company’s mobile apps.
The staggered release of Pokémon Go meant that obsessive fans in as-yet unserved regions gravitated to repackaged apps. The relatively innocuous of these apps merely contained modifications to by-pass in-app controls. However, the sheer demand for these apps also meant that unscrupulous actors were now able to get players to download versions that had either been injected with Trojans and adware or, worse still, completely repackaged malicious apps with no Pokémon code whatsoever. These repackaged apps, however, do not automatically spawn any Pokémon in regions where the official app is yet to be launched. To get around this, players had to hack API communications to spoof locations. At scale, the proliferation of repackaged apps and API abuse opens up a new vector for sophisticated DDoS attacks.
As you can see the use of in app controls can be bypassed and repackaged apps are offered and users end-up to install and use them without knowing or knowing that is not indeed the original app, but they don't mind once it's bypassing some controls that benefits the user.
So, am I saying that you shouldn't use in app controls? In my opinion you should use as many layers of defence as you can and afford in order to make the life of attackers as hard as possible, but bear in mind that if you don't combine this in-app defences with a mechanism that lets the API backend for your mobile app to know when request are from the genuine and untampered version of your mobile app, then you will end-up to fail on your efforts to thwart the attacks of the most de-terminated attackers.
Reverse Engineering Techniques
Because I'm using my app's signature as the first core security of my app. Is it possible to crack?
Yes, it can be done using static analyses via decompilation of the mobile app and/or with dynamic analyses.
An attacker may first decompile your mobile app in order to inspect the code and understand how it works and if necessary also use an instrumentation framework to to see at runtime how it behaves and how it could be bypassed in real-time.
You can learn how to use MobSF for static reverse engineering in this article I wrote:
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.
For an example on how to use an instrumentation framework at runtime you can see the article I wrote about How to Bypass Certificate Pinning with Frida on an Android App to learn how to use it:
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.
Possible Solutions
What else can i use as a password of my app that can't be seen even when decompiled? That my app will get void when that thing has changed or my app gets decompiled?
You can make it more difficult but you cannot make it impossible for being decompiled and reverse engineered. For example, you can use the built-in Proguard or R8 compiler on Android Studio:
When enabling shrinking, you also benefit from obfuscation, which shortens the names of your app’s classes and members, and optimization, which applies more aggressive strategies to further reduce the size of your app.
Obfuscation: shortens the name of classes and members, which results in reduced DEX file sizes. To learn more, go to the section about how to obfuscate your code.
A possible better solution is to shift the decision to the API backend of the mobile app, provided it works with one. The API backend will be the one deciding when to provide or not the necessary data for the app to work, but for that the backend needs to know if the requests are from what it expects, a genuine and untampered version of your mobile app.
So, if your mobile app works with an API backend then 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 where you will learn that the use of a Mobile App Attestation solution allows for the API backend to know when the request is indeed from your genuine and untampered mobile app, thus being able to deny the ones that come from tampered or repackaged versions of your mobile app, therefore rendering them useless due to the lack of data to work with.
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.
I have an Android application on Play Store and I want to detect if a user is using the original version of the app downloaded from play store or a mod apk from other sources.
Your Question
I have an Android application on Play Store and I want to detect if a user is using the original version of the app downloaded from play store or a mod apk from other sources.
A very simple question that embraces so many things to be fully answered, but from an high level view you can tackle this from within you mobile app or doing it from the outside.
Detecting from Within the Mobile app
Doing it from inside is known as 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.
One thing that I observe often is that many developers are not aware that any protection they may add to the mobile app code to try to secure it can can be bypassed during runtime with an instrumentation framework, even when the code itself is strongly obfuscated. A well known instrumentation framework used to manipulate code at runtime 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.
In the case a developer adds a function to their code to detect if the app is the original one, the attacker will eventually find it through static analysis of the binary or through dynamic analysis at runtime, and then use Frida to hook on it to change the outcome, like returning always a result that says it's the original one. Another alternative for the attacker is to recompile the binary without said function, thus removing the protection.
So, Am I saying for you to not use self protecting code or RASP solutions on your mobile app?
No, I recommend you to use all the mechanisms you can afford in order to stop the bad actors, but you also need to be aware that they can bypass them, and try to make as hard as possible to overcome your defences, to the point that it will be time consuming for them and they will just prefer to go elsewhere to look for easier targets.
Detecting from outside the Mobile App
A better alternative is to delegate to outside the app the detection when it's running or not an original version of the binary, and if it doing in a device that is not rooted or jail-broken, and this can be done by using the Mobile App attestation concept, that I explain on this answer I gave to the question How to secure an API REST for mobile app? in the section about A Possible Better Solution.
In a nutshell the Mobile App Attestion is a solution that when full implemented attests if your mobile app is the genuine and untampered version you have uploaded to the play store, and that is running in a trusted device, not jail-broken or rooted.
The Mobile App Attestation solution differs from RASP solutions in the fact that the decisions are made outside the mobile device, therefore cannot be manipulated by instrumentation frameworks, and they also issue a JWT token that allows the backend for the mobile app to know when it can trust in requests is receiving from it.
Summary
RASP solutions fall short, because usually they don't let the mobile api backend know if the request is from a genuine version of the mobile that is running in a trusted environment, aka a device not rooted or jail-broken, but even if they do that, once the logic for doing so is running inside the mobile app, it can be manipulated by the attacker with Frida or similar tools.
On the other hand a Mobile App Attestation solution will make decisions outside the mobile device and allow the mobile api backend to be aware when it can trust or not in the incoming requests.
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.
This is possible if your app is using an external server under your control providing some important functionalities to make the app useful. This might be some cloud database or an enrollment feature. For offline or device only apps the following approach will not work.
When using the SafetyNet API the SafetyNet is returning as part of the response to the server under your control a apkCertificateDigestSha256 from the app executing the call. This can be checked if it is matching your app.
Note, that the evaluationType from the response is also important. Newer devices and versions of SafetyNet are supporting here HARDWARE_BACKED making shielding frameworks like MagiskHide useless.
I have mobile app created by react native and I have backend server, which can start payment session or send e-mail when we request correct endpoint and passes correct api key. Now I'm storing backend api key in .env file, but it isn't a scurity way - https://reactnative.dev/docs/security#storing-sensitive-info
I don't want everyone who knows endpoint and will discover api key could use my backend API for example by Postman requests.
What can I do to protect my backend API in this case?
Secrets in .env file
First, you need to bear in mind that one thing is to protect secrets from leaking from the environment where you run the backend code or build you mobile app binary release, and another thing is to protect the secret when it's backed into the mobile app binary or when the mobile app is running in a mobile device.
Now I'm storing backend api key in .env file, but it isn't a scurity way - https://reactnative.dev/docs/security#storing-sensitive-info
The use of an .env file is widely used practice to avoid hardcoded secrets in your code, thus this file must be always present in the .gitignore file. Alternatives exist, like using vaults:
Harshicop Vault
Vault is a tool for securely accessing secrets. A secret is anything that you want to tightly control access to, such as API keys, passwords, certificates, and more. Vault provides a unified interface to any secret, while providing tight access control and recording a detailed audit log.
Now, this approach works very well for code that runs in a server, but for mobile app development the only advantage is that you don't have the secret hard-coded in the source code of the mobile app, thus you don't get it leaked in your Git repo(provided you have not forgot to have .env in .gitignore), but you will get the secret as normal string inside the mobile app binary, and this is so easy to reverse engineer with static binary analysis, as I describe 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.
As I say in the article, you can even use the strings command in Linux to extract it.
Orchestration Layers
https://reactnative.dev/docs/security#storing-sensitive-info
Please, don't follow this advice they made, unless:
If you must have an API key or a secret to access some resource from your app, the most secure way to handle this would be to build an orchestration layer between your app and the resource. This could be a serverless function (e.g. using AWS Lambda or Google Cloud Functions) which can forward the request with the required API key or secret. Secrets in server side code cannot be accessed by the API consumers the same way secrets in your app code can.
Why? Well how do you protect the access to that orchestration layer? From their description it seems it isn't protected, thus all an attacker needs to do is to perform a MitM attack to your mobile app in a device he controls, and learn how the app communicates with this orchestration layer, and then we can do the same outside the mobile app. The worst part is that this orchestration layer is literally open to the world, thus letting anyone to do what you are afraid of:
I don't want everyone who knows endpoint and will discover api key could use my backend API for example by Postman requests.
Reverse Proxy
Let's see the unless bit...
Now, if you protect the access to the orchestration layer with a secret, then you almost get back to square zero, but if your app is communicating with more then one backend, like using several Third Party APIs, then using a Reverse proxy(orchestration layer) is a good approach as I describe in my 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.
Secure the Secret
By now you may be wondering about how you will secure the secret to access the Reverse Proxy at runtime in your mobile app???
In the article I linked above for extracting the API key you may have noticed that I used the repo android-hide-secrets to demo some different approaches to hide them in the binary, being the most effective the one that uses Native C code. While this makes it hard to extract the secret with static binary analysis, it doesn't give you any protection against runtime attacks, like the ones that can be performed with instrumentation frameworks, 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.
With instrumentation frameworks you can even steal a secret that was stored encrypted in the mobile device with all the best state of the art techniques provided by both iOS and Android operating systems, because the attacker will hook into the function that returns the secret unencrypted for use in the request.
This is pretty scary, because with instrumentation frameworks endless possibilities to attack a mobile app at runtime, one may think it's doomed to fail to protect the code at runtime, but its not game over yet, you can still resort to the Mobile App Attestation concept, and for that I recommend you to read this answer I gave to the question How to secure an API REST for mobile app?, especially the sections Securing the API Server and A Possible Better Solution.
The Mobile App Attestation concept may be the answer you are looking for to this question:
What can I do to protect my backend API in this case?
Always, remember that security is about adding as many layers of defense as you can afford or are legally required to do. This is nothing new, just remember how castles defenses were composed of several layers.
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.
I am trying to develop a payment application using Flutter, is there any way to protect my application API's and Tokens or make app reverse engineering proof.
I am trying to develop a payment application using Flutter, is there any way to protect my application API's and Tokens or make app reverse engineering proof.
If you are looking for bulletproof solutions in the sense they are 100% effective in preventing reverse engineering a mobile app binary to extract tokens or secrets from it then I have to tell you that unfortunately, this is not possible to achieve, but you can make it harder... How hard it will depend on the effort and resources you are willing to put in or required by law for your use case.
In the other hand protecting mobile API's from being accessed from others then a genuine instance of your mobile app it is possible to achieve with a very high degree of confidence.
How easy can it be to extract an API key from a Mobile APP?
Reverse engineering a mobile app binary to extract an API token from it is very easy with the plethora of Open-Source tools out there, as I demo 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.
Alternatively, a Man in the Middle(MitM) attack can be used to extract the same API key, and for this, we also have Open-Source tools, like mitmproxy that 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.
Defending against Reverse Engineering
Reverse engineering is a huge topic and you can learn more about the techniques used in reverse engineering by reading the markdown file 0x04c-Tampering-and-Reverse-Engineering.md in the Github repo for the OWASP Mobile Security Testing Guide(MSTG).
You cannot make the mobile app 100% reverse engineering proof, but you can have a lot of hardening code techniques to make it more difficult and/or use some runtime self-protection mechanisms, aka 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.
You can read some of the possible anti-reversing defences in the OWASP MSTG repository:
Android - 0x05j-Testing-Resiliency-Against-Reverse-Engineering.md
iOS - https://github.com/OWASP/owasp-mstg/blob/master/Document/0x06j-Testing-Resiliency-Against-Reverse-Engineering.md
So, these are all approaches that make decisions in the client-side, thus prone to be bypassed by using instrumentation frameworks, 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.
Am I telling you that is worthless to use them? No, by the contrary you should add as many layers of defences as you can afford, just like how castles from the past centuries were doing to protect against the enemy breaching the outer layers of defence.
The Difference Between WHO and WHAT is Accessing the API Server
Before I dive into how you can defend your API server I would like to first clear a misconception that usually I find among developers of any seniority, that is about the difference between who and what is accessing an 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.
Lockdown the API server to the Mobile App
So, anything that runs on the client-side and needs some secret to access an API server can be abused in different ways and you can learn more on this series of articles about Mobile API Security Techniques. This articles will teach you how API Keys, User Access Tokens, HMAC and TLS Pinning can be used to protect the API and how they can be bypassed.
To solve the problem of what is accessing your mobile app you need to use one or all the solutions mentioned in the series of articles about Mobile API Security Techniques that I mentioned above and accepted that they can only make unauthorized access to your API server harder to bypass but not impossible.
A better approach can be employed by using a Mobile App Attestation solution that will enable the API server to know with a very high degree of confidence that only responds to requests from a genuine mobile app. I recommend you to read this answer I gave to the question How to secure an API REST for mobile app? that goes in more detail about it.
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.
Unfortunately, you can't. There is no way to protect a "secret" from reverse engineering if you distribute it to users. The simplest way to think about this is that a dedicated reverse engineer will be able to perfectly emulate any encryption, obfuscation, or other measures that you take. If you don't want a user to have something (such as a secret token, password, key, etc.), don't distribute it to them.
The reverse engineering protection is a gargantuan task since you have to cover both iOS and Android world specifics. Unless you decide to implement your own solution, there are various libraries (freeRASP, flutter_jailbreak_detection) solving this issue also. The downside is that if someone cracks (eg. Frida script, Magisk plugin) the library, all apps which depend on it are vulnerable also. Eg. many reverse engineering toolkits already contain bypass for popular RootBeer library. If you can't create a solution from scratch, you can use any RASP library and add your spices on top of it - RE protection should always contain as many layers as possible.
Disclaimer: I contribute to freeRASP.
Example (using freeRASP):
// For Android
androidCallback: AndroidCallback(
onRootDetected: () => exit(0),
onEmulatorDetected: () => exit(0),
onFingerprintDetected: () => exit(0),
onHookDetected: () => exit(0),
onTamperDetected: () => exit(0),
),
// For iOS
IOSCallback: IOScallback(
onSignatureDetected: () => exit(0),
onRuntimeManipulationDetected: () => exit(0),
onJailbreakDetected: () => exit(0),
onPasscodeChangeDetected: () => exit(0),
onPasscodeDetected: () => exit(0),
onSimulatorDetected: () => exit(0),
onMissingSecureEnclaveDetected: () => exit(0),
),
// Common for both platforms
onDebuggerDetected: () => exit(0),
Hovewer, attacker can locate (in the native Android/iOS code) underlying checking methods and disable them, both statically and dynamically.
From the Airwatch features and documentation, they mention that the apps are containerized. And thus, all the app content is safely encrypted and not easily exposed.
For rooted devices, Airwatch can detect such devices and perform a remote wipe of corporate data.
I wanted to check if Airwatch can guarantee that the application code cannot be reverse-engineered, to extract sensitive data from the code base, like API keys, Encryption keys etc.
I wanted to check if Airwatch can guarantee that the application code cannot be reverse-engineered, to extract sensitive data from the code base, like API keys, Encryption keys etc.
While I cannot advise you in relation to Airwatch, because I am not familiar with it, I can alert you that if you are storing this type of sensitive information in your mobile app, then you are already at risk, because reverse engineering secrets are not that hard as I show in the article How to Extract an API key from a Mobile App by Static Binary analysis:
Summary
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.
Now you may be questioning yourself as to how you would protect the API key, and for that I recommend starting by reading this series of articles about Mobile Api Security Techniques.
The lesson here is that shipping your API key or any other secret in the mobile app code is like locking the door of your home but leaving the key under the mat!
or even with a MitM attack in this other article:
Conclusion
While we can use advanced techniques, like JNI/NDK, to hide the API key in the mobile app code, it will not impede someone from performing a MitM attack in order to steal the API key. In fact a MitM attack is easy to the point that it can even be achieved by non developers.
We have highlighted some good resources that will show you other techniques to secure mobile APIs, like certificate pinning, even though it can be challenging to implement and to maintain. We also noted that certificate pinning by itself is not enough since it can be bypassed, thus other techniques need to be employed to guarantee that no one can steal your API key, and, if you have completed the deep dive I recommended, you will know by now that in the context of a mobile API, the API key can be protected from being stolen through a MitM attack. So if you have not already done it, please read the articles I linked to in the section about mitigating MitM attacks.
Also more skilled developers can hook, at run-time, some introspection frameworks, like Frida and xPosed, to intercept and modify behavior of any of your running code. So even if they are not able to decrypt your data, they will intercept the content after you have decrypted it in your application. To be able to do this, they just need to know were to hook into your code, and this they achieve by de-compiling and reverse engineer the code of your mobile app with the help of tools, like the Mobile Security Framework or APKTool, but more tools exist in the open source community.
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.
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.
APKTool
A tool for reverse engineering 3rd party, closed, binary Android apps. It can decode resources to nearly original form and rebuild them after making some modifications. It also makes working with an app easier because of the project like file structure and automation of some repetitive tasks like building apk, etc.