How to Secure an API Rest For Mobile App (If Sniffing Requests Gives You the "Key")

How to secure an API REST for mobile app? (if sniffing requests gives you the key)

Am I wrong?
Is this a stupid question?

No you are not wrong, and it's not a stupid question at all, because it's indeed easy to attack an API server of a mobile app, and you will be surprised to know how many senior developers are not aware how easy it can be done, and I have noticed that more often then not, this is due to their misconception about what vs who is accessing the API server.

The difference between what and who is accessing the API server.

This is discussed in more detail in this article I wrote, where we can read:

The what is the thing making the request to the API server. Is it really a genuine instance of your mobile app, or is it a bot, an automated script or an attacker manually poking around your API server with a tool like Postman?

The who is the user of the mobile app that we can authenticate, authorize and identify in several ways, like using OpenID Connect or OAUTH2 flows.

So if the quoted text is not enough to clarify you, then please go ahead and read the entire section of the article.

Impersonating the Mobile APP

In those request I've found a lot of auth keys that I can use in other calls from a console, simulating the app with no problems.

If by auth keys you mean the ones provide via user sign-in, with his username and password, then they just identify the who in the request.

For other keys, like api-keys, access-tokens, or any other convention used to name them, they have the purpose of providing to the API server a mechanism to only authorize requests from the genuine mobile app, they are indeed trying to allow the API server to identify what is doing the request, and has you already discovered it's easy to extract them with a proxy:

Although you use SSL, it's "usually easy" to hack mobile apps (I'm thinking in Android right now: decompiling the app, changing manifest to allow custom SSL, compiling again and sniffing through a SSL proxy all the requests).

So, in the end of the day all an attacker needs it's to use a proxy to learn how the API server works, and what is needed to simulate an API call as if it was done from the mobile app itself.

Hardening and Shielding the Mobile App

So, now I've hacked some API's in mobile apps, my question is: is there any way to secure an API in a mobile app?

You can use Mobile Hardening and Shielding solutions, that will try to prevent the mobile app to work in compromised/rooted devices, with modified/tampered apps and/or when some instrumentation framework is being used during runtime, but all of them have the draw-back of performing all that decisions in the mobile app, therefore subject to be manipulated or totally bypassed by the alreay dito instrumentation frameworks, and a good example of one it's 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.

While is better to use an in app solution, than not using anything, it's still not the ideal solution, because the control of deciding what to do is in the client side, not in the server side, thus the attacker can resort to use Frida to introspect the code at runtime and learn how to impersonate the mobile app.

Securing the API Server

The Basic API Security Defenses

Now that you understand the difference between who vs what is accessing your API server and you know that an attacker can learn how to impersonate your genuine mobile app you may want to go an read my article about the basic techniques to secure an API:

In this article we will explore the most common techniques used to protect an API, including how important it is to use HTTPS to protect the communication channel between mobile app and API, how API keys are used to identify the mobile app on each API request, how user agents, captchas and IP addresses are used for bot mitigation, and finally how user authentication is important for the mobile security and api security. We will discuss each of these techniques and discuss how they impact the business risk profile, i.e. how easy they are get around.

This is only a very basic technique that the majority of APIs may already employ, but they can be reinforced with some more advanced techniques.

More Advanced API Security Defenses

You can start to read this series of articles on Mobile API Security Techniques to understand how API keys, HMAC, OAUTH and certificate pinning can be used to enhance the security and at same time learn how they can be abused/defeated.

Afterwards, and depending on your budget and resources you may employ an array of different approaches and techniques to defend your API server, and I will start to enumerate some of the most usual ones.

You can start with reCaptcha V3, followed by Web Application Firewall(WAF) and finally if you can afford it a User Behavior Analytics(UBA) solution.

Google reCAPTCHA V3:

reCAPTCHA is a free service that protects your website from spam and abuse. reCAPTCHA uses an advanced risk analysis engine and adaptive challenges to keep automated software from engaging in abusive activities on your site. It does this while letting your valid users pass through with ease.

...helps you detect abusive traffic on your website without any user friction. It returns a score based on the interactions with your website and provides you more flexibility to take appropriate actions.

WAF - Web Application Firewall:

A web application firewall (or WAF) filters, monitors, and blocks HTTP traffic to and from a web application. A WAF is differentiated from a regular firewall in that a WAF is able to filter the content of specific web applications while regular firewalls serve as a safety gate between servers. By inspecting HTTP traffic, it can prevent attacks stemming from web application security flaws, such as SQL injection, cross-site scripting (XSS), file inclusion, and security misconfigurations.

UBA - User Behavior Analytics:

User behavior analytics (UBA) as defined by Gartner is a cybersecurity process about detection of insider threats, targeted attacks, and financial fraud. UBA solutions look at patterns of human behavior, and then apply algorithms and statistical analysis to detect meaningful anomalies from those patterns—anomalies that indicate potential threats. Instead of tracking devices or security events, UBA tracks a system's users. Big data platforms like Apache Hadoop are increasing UBA functionality by allowing them to analyze petabytes worth of data to detect insider threats and advanced persistent threats.

All this solutions work based on a negative identification model, by other words, they try their best to differentiate the bad from the good by identifying what is bad, not what is good, thus they are prone to false positives, despite of the advanced technology used by some of them, like machine learning and artificial intelligence.

So, you may find yourself more often than not in having to relax how you block the access to the API server in order to not affect the good users. This also means that this solutions require constant monitoring to validate that the false positives are not blocking your legit users and that at same time they are properly keeping at bay the unauthorized ones.

Regarding APIs serving mobile apps a positive identification model can be used by implementing a Mobile App Attestation solution that attests the integrity of your mobile app and device its running on before any request is made to the API server.

A Possible Better Solution

The role of a Mobile App Attestation service is to authenticate what is sending the requests, thus only responding to requests coming from genuine mobile app instances and rejecting all other requests from unauthorized sources.

In order to know what is sending the requests to the API server, a Mobile App Attestation service, at run-time, will identify with high confidence that your mobile app is present, has not been tampered/repackaged, is not running in a rooted device, has not been hooked into by an instrumentation framework(Frida, xPosed, Cydia, etc.), and is not the object of a Man in the Middle Attack (MitM). This is achieved by running an SDK in the background that will communicate with a service running in the cloud to attest the integrity of the mobile app and device it is running on.

On a successful attestation of the mobile app integrity, a short time lived JWT token is issued and signed with a secret that only the API server and the Mobile App Attestation service in the cloud know. In the case that attestation fails the JWT token is signed with an incorrect secret. Since the secret used by the Mobile App Attestation service is not known by the mobile app, it is not possible to reverse engineer it at run-time even when the app has been tampered with, is running in a rooted device or communicating over a connection that is the target of a MitM attack.

The mobile app must send the JWT token in the header of every API request. This allows the API server to only serve requests when it can verify that the JWT token was signed with the shared secret and that it has not expired. All other requests will be refused. In other words a valid JWT token tells the API server that what is making the request is the genuine mobile app uploaded to the Google or Apple store, while an invalid or missing JWT token means that what is making the request is not authorized to do so, because it may be a bot, a repackaged app or an attacker making a MitM attack.

A great benefit of using a Mobile App Attestation service is its proactive and positive authentication model, which does not create false positives, and thus does not block legitimate users while it keeps the bad guys at bay.

The Mobile App Attestation releases your mobile app from having an embedded secret in its code, instead now it only needs to pass to the reverse proxy or backend the JWT token it receives from the mobile app attestation service. Now the reverse proxy or backend can verify the JWT token, and on successful validation they can accept requests with a very high confidence that they are originated from what they expect, a true and genuine instance of the mobile app, with the added benefit of not exposing the API keys to access your API server or any Third Party services.

GOING THE EXTRA MILE

I cannot finish without recommending you the excellent work done by the OWASP foundation.

For Mobile Apps

OWASP - Mobile Security Testing Guide:

The Mobile Security Testing Guide (MSTG) is a comprehensive manual for mobile app security development, testing and reverse engineering.

For APIS

OWASP API Security Top 10

The OWASP API Security Project seeks to provide value to software developers and security assessors by underscoring the potential risks in insecure APIs, and illustrating how these risks may be mitigated. In order to facilitate this goal, the OWASP API Security Project will create and maintain a Top 10 API Security Risks document, as well as a documentation portal for best practices when creating or assessing APIs.

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

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.

How to protect public APIs (no credentials) from being exploited?

Short Live JWT Tokens

Can we have "anonymous" users that have a short-lived JWT token?

Yes, you can and its recommend that you even do it for logged users. See the Auth0 blog What Are Refresh Tokens and How to Use Them Securely:

This post will explore the concept of refresh tokens as defined by OAuth 2.0. We will learn how they compare to other token types and how they let us balance security, usability, and privacy.

The problem with using tokens for anonymous users or logged in users is that they only identify who is in the request, not what is doing the request.

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 (anonymous or logged) 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.

Your Possible Solutions

We are already considering:

  • API KEY for every application (not per session)
  • Rate limiting
  • DDoS services to protect the APIs

This are basic security measures that any API should implement, but they will fall short when it comes to give na high degree of confidence to API server that the request is indeed from what it expects, a genuine and untampered version of your app.

You can read more about in my article The Top 6 Mobile API Protection Techniques - Are They Enough?:

In this article we will explore the most common techniques used to protect an API, including how important it is to use HTTPS to protect the communication channel between mobile app and API, how API keys are used to identify the mobile app on each API request, how user agents, captchas and IP addresses are used for bot mitigation, and finally how user authentication is important for the mobile security and api security. We will discuss each of these techniques and discuss how they impact the business risk profile, i.e. how easy they are get around.

The reader will come to understand why today’s commonly used mobile API protection techniques are very naive and not fit for purpose to defend digital businesses against API abuse. API abuse is its various forms is much more commonplace that most businesses realize so it is important to employ the right techniques to maintain revenue and brand reputation.

Other Possible solutions

For example, how can the SPA Web application or Mobile application securely obtain a "per-session" anonymous user?

With web apps its very easy to introspect them and see the API requests and their responses by just using the developer tools on the browser.

For mobile apps more work its required but a plethora of open source tools exist to make it easy and in some cases trivial to the point that even non developers can do it, thus making the task of securing an API server very hard, but not impossible.

So, do to the completely different way how the web and mobile devices work the approaches to secure them will differ.

For Web Apps

Are Captchas actually helpful in this scenario?

Captcha gives you a score to tell you a likely who is in the request is a real human. At the best score it cannot guarantee with an high degree of confidence that what is doing the request is indeed what your API server expects, a genuine and untampered version of your web or mobile app.

To learn some useful techniques to help your API backend to try to respond only to requests coming from what you expect, your genuine web app, you can read my answer to the question Secure api data from calls out of the app, especially the section dedicated to Defending the API Server.

For Mobile Apps

It's more of a general question, but What is the recommended way to protect APIs used in SIGN UP processes?

Despite not being specifically for the signup process 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.

From that answer the better approach that can be employed is by using a Mobile App Attestation solution that will enable the API server to know is receiving only requests from what it expects, a genuine and untampered version of your mobile app.

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 Web Apps

The Web Security Testing Guide:

The OWASP Web Security Testing Guide includes a "best practice" penetration testing framework which users can implement in their own organizations and a "low level" penetration testing guide that describes techniques for testing most common web application and web service security issues.

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

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.

Sample Image

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.

how to secure an API when called by Android app

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

Related Topics



Leave a reply



Submit