DEV Community

Cover image for I am a Developer Advocate for Security in Mobile Apps and APIs, Ask Me Anything
Paulo Renato
Paulo Renato

Posted on

I am a Developer Advocate for Security in Mobile Apps and APIs, Ask Me Anything

Try me for your questions about Mobile API Security!

Latest comments (26)

Collapse
 
wolfiton profile image
wolfiton

Hi @paulorenato,

You are still interested to discuss mobile and web security I have a case that I couldn't find a reliable solution so far.

Imagine the following stack:

Graphql
SSR App - NuxtJS
PWA - feature

How to deny the users access when the app goes in PWA mode(offline) or allow only the index action?

Can the auth be something else than a JWT? (paseto doesn't work because it needs the server for decrypting the token)?

How secure can a JWT auth app be for Stripe payments?

Some ideas I have related to JWT:

  • They are not secure
  • can be tampered
  • need to check also server-side
  • never trust data from the client(NUXTJs) in this case.
  • always try to encrypt them
  • problems when storing them in local storage

I think the main question is this:

Given these problems should an application be built-in Graphql SSR and PWA or is it better to just have a backend and some javascript to make a better user experience in some areas?

Collapse
 
exadra37 profile image
Paulo Renato • Edited

PWA and Offline Mode

How to deny the users access when the app goes in PWA mode(offline) or allow only the index action?

I know what a PWA is, but I have no experience with it, thus I cannot be of great help here, but as I always like to say an app should be as dumb as possible and leave the business logic to the server, and just worry about the presentation layer.

So I would say that if you need to restrict access to content by user, then the offline model will not be the one you want to use in any kind of technology of your choice. I say this because once the data is in the client side, it's public and should be considered as leaked. No matter the amount of measures you put in place it will be just a question of time and skills to reverse engineer the logic restricting the access to the data and bypass it to extract the protected data. This is even easier in browser based apps, but also doable in mobile apps that as you may know are compiled to binary format.

The Difference Between WHO and WHAT is Accessing the API Server

Before I dive into your other questions I would like to first clear a misconception about 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.

JWT Security

Some ideas I have related to JWT:
They are not secure

They are secure when you sign them, and in this moment the correct term to use is JWS. Signing them only serves to guarantee the recipient it's intended to that the payload of it was not tampered with, but will not protect the payload from being extract and used.

JWS

A JSON Web Signature (abbreviated JWS) is an IETF-proposed standard (RFC 7515) for signing arbitrary data.[1] This is used as the basis for a variety of web-based technologies including JSON Web Token.

If you need to hide the payload data because it contains sensitive data then you want to also encrypt the payload part of the token, and at this moment you should call it a JWE.

JWE

JSON Web Encryption (JWE) is an IETF standard providing a standardised syntax for the exchange of encrypted data, based on JSON and Base64.[1] It is defined by RFC7516. Along with JSON Web Signature (JWS), it is one of the two possible formats of a JWT (JSON Web Token). JWE forms part of the JavaScript Object Signing and Encryption (JOSE) suite of protocols.

When a JWE it's used the payload cannot be decrypted, unless you have used a weak encryption algorithm or you have leaked the encryption keys.

Some ideas I have related to JWT:
can be tampered

If using JWS or JWE they cannot be tampered without you detect it on the validation.

Some ideas I have related to JWT:
need to check also server-side

That for what they were designed, aka the recipient using it needs to validate it with a public key or with the shared secret only known by the sender and the receiver.

Some ideas I have related to JWT:
never trust data from the client(NUXTJs) in this case.

That true for literally ANY client.

Some ideas I have related to JWT:
always try to encrypt them

It depends if they contain or not sensitive data.

Some ideas I have related to JWT:
problems when storing them in local storage

Local storage in browsers is always a problem, because Javascript can always access them.

Web Apps

Given these problems should an application be built-in Graphql SSR and PWA or is it better to just have a backend and some javascript to make a better user experience in some areas?

I am from the time that the web app development was simpler, and I also got into the bandwagon of building web apps with as much logic as possible on the client side and backed by an API, but from the moment I got into API security I just realized how hard is to secure API backends serving them, thus the web app that I am building now it's using session cookies and no API, just a traditional web server in Elixir with the Phoenix Framework, but off course this in my peculiar situation that I am not planning for mobile app releases, but even If I decide to add a mobile app later I wrote the backend code in a way that will be easy to extend to create an API from the web server, because the business logic is separated from the presentation layer.

My take on web apps since I got into API security in 2018 is to use Javascript only for the presentation layers, aka to manipulate the HTML DOM and enrich the user interactivity. Business logic belongs to the backend.

So my recommendation is to carefully think if you really need to build an API for your web app, and that web apps should not be using JWT tokens if they are not using an API, because a web app that gets server side rendered html is best served in terms of security with the use of session cookies with http only flag set, that will prevent Javascript to access them.

Collapse
 
wolfiton profile image
wolfiton • Edited

Thanks for sharing your take on this. I am also glad that someone else uses phoenix and elixir in their stack.

Regarding the jose standard for jwt, I was looking at paseto but never managed to make it working with laravel. the good news is that Elixir has a paseto package and might be worth looking at it if you want a powerfull security with SSR.

Also is SSR possible with http only cookies, because i couldn't find anything related to this, have you tried it?
Just found this and i am wondering if it is secure enough to be able to use it to leverage SSR for seo and security with the auth header cookie
swapnil.dev/blog/authentication-in...
Also sorry if I write so much, I am just very happy that I could find someone that is very knowledgeable regarding security and can understand my worries of the new web stacks that everybody is so thrilled about.
Thanks in advance

Thread Thread
 
exadra37 profile image
Paulo Renato

Also is SSR possible with http only cookies, because i couldn't find anything related to this, have you tried it?

Well be it server side rendered or not httpOnly cookies are not controlled by your app in the client side, instead it's the browser the one in charge of sending them back in each request to the backend, therefore you just need to check them on each request your backend receives:

From Mozilla:

Ways to mitigate attacks involving cookies:

  • Use the HttpOnly attribute to prevent access to cookie values via JavaScript.
  • Cookies that are used for sensitive information (such as indicating authentication) should have a short lifetime, with the SameSite attribute set to Strict or Lax. (See SameSite cookies, above.) In browsers that support SameSite, this has the effect of ensuring that the authentication cookie is not sent with cross-origin requests, so such a request is effectively unauthenticated to the application server.

Also remember to always encrypt the session cookies in your backend so that no one can spy on them, thus mitigating what Mozilla mentions:

Security

Information should be stored in cookies with the understanding that all cookie values are visible to, and can be changed by, the end-user. Depending on the application, it may be desirable to use an opaque identifier which is looked-up by the server or to investigate alternative authentication/confidentiality mechanisms such as JSON Web Tokens.

So if you decide to put the JWT in a session cookie, then use JWE, aka encrypted JWT's... This is what I am doing in my Elixir/Phoenix app.


the good news is that Elixir has a paseto package and might be worth looking at it if you want a powerfull security with SSR.

No need to use Paseto with Phoenix in Elixir, just use the native encrypted tokens.


Thanks for sharing your take on this. I am also glad that someone else uses phoenix and elixir in their stack.

Professionally I code in a lot of different languages, personally only in Elixir ;)

Collapse
 
bmitch profile image
Bill Mitchell

What are some good resources (besides your posts :) ) for those interested to learn more about mobile API security?

Collapse
 
exadra37 profile image
Paulo Renato • Edited

Hi Bill,

Thanks for asking ;)

With no order of preference, and with focus on security:

apisecurity.io/

APISecurity.io is a community website for all things related to API security. Our daily news and weekly API Security newsletter cover the latest breaches, vulnerabilities, standards, best practices, regulations, and technology.

apisecurity.io/encyclopedia/conten...

API Security Encylopedia collects together information on the risks, guidelines, and recommendations relating to API security.

For developers with focus on API security for mobile apps I recommend to read this series about Mobile API Security Techniques and to follow the api tag in the blog of my workplace, where I and some of my colleagues write about API security with focus on mobile clients.

OWASP API Security Top 10

owasp.org/index.php/OWASP_API_Secu...

A foundational element of innovation in today’s app-driven world is the API. From banks, retail and transportation to IoT, autonomous vehicles and smart cities, APIs are a critical part of modern mobile, SaaS and web applications and can be found in customer-facing, partner-facing and internal applications. By nature, APIs expose application logic and sensitive data such as Personally Identifiable Information (PII) and because of this have increasingly become a target for attackers. Without secure APIs, rapid innovation would be impossible.

github.com/OWASP/API-Security

This project is designed to address the ever-increasing number of organizations that are deploying potentially sensitive APIs as part of their software offerings. These APIs are used for internal tasks and to interface with third parties. Unfortunately, many APIs do not undergo the rigorous security testing that would render them secure from attack.

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.

Keep up to date with the latest API trends

nordicapis.com/blog/

Learn how to make smarter tech decision using APIs. The resource for API practitioners.

Collapse
 
bmitch profile image
Bill Mitchell

What is your favourite food?

Collapse
 
exadra37 profile image
Paulo Renato

Not a valid question... moving on!!!

Ok, if you insist, it's Portuguese food, but don't ask me why...

Collapse
 
bmitch profile image
Bill Mitchell

😂

Collapse
 
vlainvaldez profile image
bugbot

If I will be building a fintech related app, what are the securities I need to have (ex. Library, Encryption etc.) for me to have a better level of security for my android and iOS apps, I know this is vague but Im still searching for best practices for security in mobile apps

Collapse
 
exadra37 profile image
Paulo Renato

Your Problem

If I will be building a fintech related app, what are the securities I need to have (ex. Library, Encryption etc.) for me to have a better level of security for my android and iOS apps

Fintech is one of that use cases were security is mandatory and must be a first class citizen from day zero in any project, thus I need to present my congratulations to you for being so diligent in security.

I know this is vague but Im still searching for best practices for security in mobile apps

A common problem among developers is that they focus to much in just one side of the equation. When building a mobile app you usually need an API server, and the security strategy must be aligned between both sides.

Lets' clear first a usual misconception among developers, that relates to WHO vs WHAT is accessing the API server.

The Who vs What Is Accessing the API Server

For a better understanding off the difference between WHO vs WHAT is accessing your API server, I recommend you to read this section of my article, but I will extract here some lines of it:

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

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

Public vs Private APIs

Let me tell you here a cruel truth... Private APIs don't exist!!!

No matter if an API doesn't have public accessible documentation or if is is protected by any kind of secret or authentication mechanisms, once is accessible from the Internet is not private any-more, and you even have tooling to help with discover them.

You can read more about it in this article section, and I extract to here some bits:

Now just because the documentation for your API is not public or doesn’t even exist, it is still discoverable by anyone having access to the applications that query your API.

Interested parties just need to set up a proxy between your application and the API to watch for all requests being made and their responses in order to build a profile of your API and understand how it works.

A proxy tool:

MiTM Proxy

An interactive TLS-capable intercepting HTTP proxy for penetration testers and software developers.

So the lesson here is that from the moment you release a mobile app that uses your API, you can consider it to belong now to the public domain, because anyone can reverse engineer it and discover how your "private" API works, and use that to build automated attacks against it.

Mobile Apps Binaries are Public

From the moment you release your mobile app you can consider everything inside of it to belong to the public domain.

Oh but I obfuscated it, I encrypted it and so on and so forth, but you need to bear in mind that this only makes it hard to reverse engineer, not impossible. So you get ride of script kids and seasonal hackers, but you don't get ride from skilled ones that are willing to put the effort and necessary time to reverse engineer your app, provided that they can profit from it, and we have tools to help with the task:

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.

Mobile Apps Should be Dumb

A common mistake among developers is to have business logic inside their mobile app...

Yes it's a mistake because once a mobile binary is public it can be reverse engineer.

Instead you should delegate as much as possible all business logic to the API server, because you also have the threat of instrumentation frameworks that can hook into your mobile app during run-time to change the business logic in order to change the outcome of it.

Frida

Inject your own scripts into black box processes. Hook any function, spy on crypto APIs or trace private application code, no source code needed. Edit, hit save, and instantly see the results. All without compilation steps or program restarts.

xPosed

Xposed is a framework for modules that can change the behavior of the system and apps without touching any APKs. That's great because it means that modules can work for different versions and even ROMs without any changes (as long as the original code was not changed too much). It's also easy to undo.

Plus this approach have the benefit of helping you to fix bugs quickly without the need to release a new version of your mobile app, and wait for everyone to update or use a kill switch to force them to update.

In my previous work we used this strategy with a huge success, and this was for e-commerce mobile apps for the UK biggest retailers.

Mobile Apps and Third Part APIs

Try to NEVER access third part services in your mobile app, instead always delegate it to your API server, unless is technically impossible.

Why?

Well access to third part service need some kind of secret, and once mobile app binaries are public your secrets are not secrets anymore, even if you hide them in native C code with JNI/NDK or in the native secure storage, because you can use instrumentation frameworks to hook into you mobile app at runtime and extract that secrets or encryption keys.

The lesson to take here is that as a best practice a mobile app should only communicate with an API server that is under your control and any access to third party APIs services must be done by this same API server you control. This way you limit the attack surface to only one place, where you will employ as many layers of defense as what you are protecting is worth.

The Basic API Security Defenses

Now that you understand the difference between who vs what is accessing your API server 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.

More Advanced API Security Defenses

You can start by 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 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.

Mobile App attestation

Finally if you have the resources you can go even further, by building your own Mobile APP Attestation 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.

Conclusion

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 API server under your control, so that you reduce the attack surface, and at the same time protect their secrets from public pry eyes.

In my opinion the best solution is defense in depth, by applying as many layers as you can, so that you increase the time, effort and skill-set necessary to by pass all your security layers, thus keeping at bay the script kids and occasionally hackers from abusing your service.

So you should employ has much techniques as possible in both sides of the equation, mobile app and API, like the ones you have learned when reading the articles I have linked: HTTPS, API keys, User Agents, Captchas, Rate Limiting, OAuth, HMAC, Certificate Pinning, Code Obsfuscation, JNI/NDK to hide secretes, WAF, UBA, etc.

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.

Going the Extra Mile

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.

Collapse
 
zawawimanja profile image
zawawimanja

frida is powerful tools. If you can please make an article or tutorial about how to hook or how to use it.

Thread Thread
 
exadra37 profile image
Paulo Renato

Yes its a very powerful tool, and its in my TODO list to do an article with it ;)

Collapse
 
jess profile image
Jess Lee

A couple questions:

  • What does the interview process look like for security engineers?
  • What's the hardest part about advocating for security?
Collapse
 
exadra37 profile image
Paulo Renato • Edited

What does the interview process look like for security engineers?

I am not responsible for hiring, but I know that when they hired me for the Developer Advocate position, they where looking for an individual with a security mindset and with coding skills in the API and Mobile Apps landscape. In my case I had to do a presentation where I would evaluate a demo the company uses and show my knowledge around certificate pinning in mobile apps. They gave me around 2 weeks to prepare for it, and as part of that preparation I wrote some notes here.

When the CTO is back from holidays I can ask him what is more important to him when hiring a security engineer.

What's the hardest part about advocating for security?

It's that people think that only happens to others, and that we are being paranoid, and this even after you present with some links to concrete cases of monumental failures of addressing the security basics in a project.

Becomes easier to advocate when your audience already have felt in their skin the experience of their application being hacked, but even in this situation you still have developers and businesses refusing to treat security as a first class citizen.

Security must be present in a project from day zero, not as an afterthought, because you after have built your prototype, and more often than not, it will become the MVP(Minimal Viable Product), thus making more difficult to add security into it due to decisions made in earlier stages.

Collapse
 
anwar_nairi profile image
Anwar

Hi Paulo,

Great to give some of your time for our questions!

Mine is about something I read on reddit saying JWT tokens are not safe to use to keep the user authenticated. It is said that Pasteo is safer, I also read that keeping the token in the cookie session is safer than storing the token in localStorage.

What do you think about it? I also wondered if I encrypt my token before sending it to my client browser will make it harder to decrypt, is this enough to keep using a stateful JWT (because I have my user ID inside) to authenticate my users?

Collapse
 
exadra37 profile image
Paulo Renato

Mine is about something I read on reddit saying JWT tokens are not safe to use to keep the user authenticated.

Can you share the link in order to give more insight to the scope of that affirmation?

But as in many things it depends for what you are using JWTs and how you use them. Can you give me some more insight in your use case?

It is said that Pasteo is safer

You mean Paseto? Never seen it before, but looks interesting, need to take a better look into it.

I also read that keeping the token in the cookie session is safer than storing the token in localStorage.

You mean browser localStorage?

If you are use case is just for a web app and a web backend, then I would stick with secure and HttpOnly cookies.

What do you think about it? I also wondered if I encrypt my token before sending it to my client browser will make it harder to decrypt, is this enough to keep using a stateful JWT (because I have my user ID inside) to authenticate my users?

Where is comming your JWT from? An OAUTH provider or is provided by your own backend?

Without knowing more about your use case is hard to make a best recommendation, but as already said if is a web app with only a web backend I would not go with JWTs, and instead stick with session cookies, as I linked above.

Collapse
 
anwar_nairi profile image
Anwar • Edited

The link where I read JWT is not a good medium for keeping users authenticated : cryto.net/~joepie91/blog/2016/06/1... (came from a paragonie post about promoting Paseto).

My use case is a shop web app (hosted on example.com) where the user can log in and keep track of his orders and loved products. I use Vuejs in the fron end and an API for the backend (powered by Laravel). For the moment I used JWT stored in the browser local storage, and keep using Post request with the token in parameter to validate the authenticity of the token (and keep the user ID inside of my token in the appropriate key).

When my user validate a login form, the credentials are sent to my Auth validation endpoint (api.example.com/auth), and if they are valid, I send back the token forged using firebase/jwt. I pass the encrypted user ID inside of my JWT, and I also encrypt the whole JWT string (using laravel facade method Crypt::encryptString).

Every time the user needs to make an action (like putting a love to a product for example), I decrypt the token, check its if it's valid, decrypt the user ID, and if the user exists, persist the favorite product in database.

I guess I could use http only cookies to pass the token instead of providing it at each requests.

Do you think this process is secure enough? Should I go something different for my use case?

Thank you so much for your time, I learn a lot right now!

Thread Thread
 
exadra37 profile image
Paulo Renato • Edited

Thanks for the detailed explanation.

Do you think this process is secure enough? Should I go something different for my use case?

I would prefer to use session cookies with httpOnly flag set, because local storage can be accessed via javascript and httpOnly cookies cannot, aka they are automatically sent back by the browser in each request performed to your web backend, but while more safe they are not bullet proof against abuse from an attacker.

Please keep reading to understand the difference between WHO and WHAT is accessing your web backend, and then thinks sill start to make more sense.

Requests Trust and the WHO vs the WHAT

Please keep in my mind that you cannot blindly trust in any kind of secret is presented to your backend to authenticate a user or what is making the request.

To better understanding what I mean you need to know the difference between WHO vs WHAT is accessing your API server, as I explain here, where you can read:

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

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

This is only an excerpt, thus I recommend you to read the full section I linked to better grasp the differences.

How Can I Defend My Backend

While more in the context of an API, lot of what I recommended in this #ama reply is valid for a web backend to.

Please keep in mind that encrypting the JWT tokens only gives you confidentially during the request life cicle, aka no one will be able to read what is inside, but will not give you authenticity, aka guarantee that WHAT is sending back the encrypted JWT is really your web app in the behalf of WHO a JWT represents, aka your user.

Thread Thread
 
anwar_nairi profile image
Anwar • Edited

An absolute thank you for all those information, I have now more information about differenciation between the what and the who. I was only checking the what until now but cannot for sure ensure who is sending the token. I will have a deep look at your links, I also seen some other folks have more detail explanation and I will take note of those too. Thank you fine sir!

Thread Thread
 
exadra37 profile image
Paulo Renato

You got it the other way around...

The who represent the user, your JWT token and the what represents the mechanism used to make the request, aka was the request made by your web app without have been tampered, was the request made by Postman or by Curl, etc..

So until now you have been checking the who, aka the JWT token that represents the user authentication,

Collapse
 
karandpr profile image
Karan Gandhi

Ohai. So here is my question.
How do you restrict Mobile API to package-name ?
And, apart from SafetyNet, which are other mobile app attestation techniques ?

Collapse
 
exadra37 profile image
Paulo Renato

How do you restrict Mobile API to package-name ?

You mean how do only make your API server to only accept requests from your mobile app?

And, apart from SafetyNet, which are other mobile app attestation techniques ?

SafetyNet is not a mobile app attestation technique, because it only attests the mobile device, not the mobile app.SafetyNet is primarily designed to check if the OS image that a particular Android device is running is considered to be secure and compatible or not, you can think of it as an advanced root check.

So SafetyNet cannot tell if your mobile app have been tampered with, is being MitM attacked or have an instrumentation framework hooked to modify its behavior during run time, like Frida, xPosed or Magisk. Where I work we have a small report in pdf format that can explain it in more detail.

Collapse
 
karandpr profile image
Karan Gandhi

Sorry about the lack of details.
1.) Yeah I was thinking Google APIs or Firebase. We can restrict APIs to Mobile Application package name, viz., com.package.name. Going a step further how to restrict certain API endpoints to signing keys.

2.)Interesting. Let me reframe the question. What attestation techniques can I use to secure my API ?

Thread Thread
 
exadra37 profile image
Paulo Renato

Question 1

1.) Yeah I was thinking Google APIs or Firebase. We can restrict APIs to Mobile Application package name, viz., com.package.name. Going a step further how to restrict certain API endpoints to signing keys.

I have no experience at all with Google APIs, thus cannot help here.

Regarding Firebase I just took a quick look some weeks ago and for what I can tell you cannot hook custom scripts for each incoming request, thus you cannot implement aditional security measures, like a Mobile App Attestation solution.

Question 2

2.)Interesting. Let me reframe the question. What attestation techniques can I use to secure my API ?

The Who vs What Is Accessing the API Server

You can start with understanding the difference between WHO vs WHAT is accessing your API server, as I explain here, where you can read:

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

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

The Basic API Security Defences

Now that you understand the difference between who vs what is accessing your API server 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.

More Advanced Security Defences

Afterwards you can get a little more deep and read the series 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 how they can be abused/defeated.

You can also resort to a WAF(Web Application Firewall) or A UBA(User Behaviour Analytics) that will use machine learning and Artificail intelligence to detect bad requests into your API server. This ones have the downside of blocking some good requests while letting some bad ones to pass by, thus they require constant monitoring to adjust security policies and filters.

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.

Possible Solutions

In my opinion the best solution is defence in depth, by applying as many layers as you can, so that you increase the time, effort and skill-set necessary to by pass all your security layers, thus keeping at bay the script kids and season hackers from abusing your service.

So you should employ has much techniques as possible from the ones you have learned when reading the articles I have linked, like HTTPS, API keys, User Agents, Captchas, Rate Limiting, OAuth, HMAC, Certificate Pinning, Code Obsfuscation, Secretes hidden in native C code with JNI/NDK, WAF, UBA, etc.

Finally if you have the time you can go even further by building your own Mobile APP Attestation 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 service already exists as a SaaS solution at Approov . The solution supports SDKs for several platforms, including iOS, Android, React Native and Cordova. To deploy, a small check in the API server code to verify the JWT token issued by the Approov cloud service is needed. This check is how the API server authenticates what is making the request.

When correctly implemented a Mobile APP Attestation solution have the advantage of not requiring constant monitoring to not block good requests to your API server.

Conclusion

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.

Thread Thread
 
karandpr profile image
Karan Gandhi

Thanks for the detailed reply. Much Appreciated.