Should I explicitly not use a standard URL with MSAL authentication? - azure-active-directory

All of the MSAL documentation wants me to use a prefix such as msalGUID:/// when authenticating back to the local device.
Then there is the oddball url urn:ietf:wg:oauth:2.0:oob that appears by default in the MSAL portal.
Since every URL I list there is essentially a backdoor into my application, I want to understand the security benefit of each option.
Why should I use the documented msalGUID:// scheme?
Should I not use an iOS Universal Link / fully qualified URL?
What is the benefit of the urn:ietf:wg:oauth:2.0:oob, and https://login.live.com/oauth20_desktop.srf?
What should I be aware of w.r.t. interactions with Microsoft Authenticator, which likely depends on this?

Background
There's a few attack vectors & usability cases that come into play when considering the redirect URI your app will use.
First, is your app going to be signing in users from an authorization agent that is not sandboxed to your app. If you're using MSAL, then the answer is almost always yes (unless you have explicitly opted to use in-app WebViews).
Cases to consider
If so, then you have two cases to consider: accidental collisions of redirect URIs (usability issue) and malicious apps intentionally trying to intercept a user being redirected back to your app (security issue).
Case 1: Naive apps
To address the former, MSAL has chosen msal<ClientID>://auth as it's unique to each app registration. There's a high amount on randomness in this format (that is lost with urn:ietf:wg:oauth:2.0:oob) which prevents the scenario in which multiple apps on the device are listening on the same URI and "accidentally" get the response. For a user, this is extremely frustrating and would impact their experience with their app. To summarize the best practice to address this, use a highly random URI that avoids accidental collision with other apps.
Case 2: Malicious apps
To address the latter, MSAL implements the Proof Key for Code Exchange (PKCE) protocol to eliminate this attack vector. To expand on the scenario, it's similar to the above scenario, except for the app has captured the response intentionally and intends to exchange the authorization code on your behalf. With PKCE, only the app that initiated the request can exchange the auth code.
Summarizing answers
To quickly answer your bullets,
Covered above.
If you're familiar with universal links and how to setup the necessary steps, this may be a good option for verifying that your app registration is only used by you.
These are intended for apps using in-app WebViews where there's stronger security guarantees related to the fact it's not leaving the app.
MSAL does not currently integrate into the Authenticator to complete auth requests. When it does, apps will likely be required to complete an enhanced registration related to redirect URIs similar to ADAL's requirements.

Related

passport js vs firebase authentication system

Is there any valid reason to use passport js based authentication using express js in backend over firebase authentication system in frontend using react?
just explored passport js and want to know before using in a MERN Stack project
PassportJS is just an authentication middleware that can be used with different authentication strategies. If I understood you correctly you might be comparing Passport's local strategy with Firebase auth's username/password one, in this case:
My answer would be a classical "IT DEPENDS", first I will answer the first part:
Why use Firebase-auth (or any other third-party authentication service)
Authentication is hard, and you may not want to deal with it on your own (most of the time).
If you are planning to use a "local" authentication strategy with a username/email and a password, you might need to consider and maintain a set of best practices to avoid having a broken-authentication system, you will need to encrypt your passwords and ensure that they're safe on at-rest and in-transit, you also want to ensure that your system uses libraries or logic to avoid timing attacks. Also, you may need to consider forcing some rules on password lengths and that they're not too weak (ex: they belong to a list of most-known passwords)...
Besides these, you may also want to implement password recovery mechanisms, email change, and maybe "Email confirmation" logic which might be tricky sometimes.
Did I forget to mention reCaptcha and 2FA? Bots are getting smarter nowdays.
I definitely missed some other best practices or risks that should be considered when not using a managed service like Firebase-auth.
These services are built by people who only care about "Authentication" for you.
Firebase-auth is not the only service, you may want to look into other options like auth0.
Of course, this option is not the cheapest in terms of cost and flexibility. Firebase auth has a generous free tier, but it will be paid when your application grows, see: https://firebase.google.com/pricing.
So, if you go with this option, consider organizing your application code to be easily decoupled from Firebase in case you wanted to migrate from it someday.
Why use Passport-local
Using the middleware on your own means that you will have more flexibility in managing your different authentication strategies and you will only pay an extra cost of maintaining your application's authentication logic (which might be high as you need to keep in mind the best practices and risks)
Other considerations
This depends on your use case, and your team:
You may look into some services that handle the authentication out of the box like Keycloak
Use Passport.js as a core library but with strategies like Auth0's (https://www.passportjs.org/packages/passport-auth0/)

How to protect my own api from hacking and make it private, so no body can access it exept from the android app?

I have written my own api and I want to upload it to the server but I want to secure it so noone can access it except from my app, I have tried slim-basic-auth library but it didn't work, I don not know why...
any help with that please ?
$app->add(new Tuupola\Middleware\HttpBasicAuthentication([
"secure"=>false,
"users" => [
"userher##" => "passhere##" ]
]));
I think you will never be able to hide the api url being called by the app (an attacker with rooted android device can intercept traffic easily ), If your api response user specific data, you can add auth header in request and same verify this header at server. You can also use Cross-Origin Resource Sharing-CORS and SSL for extra layer of security.
YOUR QUESTIONS
In a glance you want to have a private API, lock your Android App to it, and solve your code issue in the API server. Let's address each one in the order I mentioned them.
PRIVATE APIs
How to protect my own api from hacking and make it private
Well I have a cruel truth to reveal to you, no such thing as a private API exists, unless you don't expose it to the Internet, aka only have it accessible inside a private network, via programs that themselves are not expose also to the internet. By other words your API can only be private if its is air gaped from the internet.
So 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.
HOW TO LOCK AN API TO AN ANDROID APP
I have written my own api and I want to upload it to the server but I want to secure it so noone can access it except from my app
Well you bought yourself a very hard task to accomplish, that some may say that its impossible to do, but once you dig deep enough in the subject, you will be able to understand that you still have some paths to explore.
First you will need to understand the difference between WHO and WHAT is accessing your API server, followed by learning some of the most common techniques used to secure an API server, and finally you will learn that the Mobile App Attestation may be what your are looking for.
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 WAHT is accessing your API server, but I will extract here the main take aways from it:
The what is the thing making the request to the API server. Is it really a genuine instance of your mobile app, or is it a bot, an automated script or an attacker manually poking around your API server with a tool like Postman?
The who is the user of the mobile app that we can authenticate, authorize and identify in several ways, like using OpenID Connect or OAUTH2 flows.
So think about the WHO as the user that your API server will be able to Authenticate and Authorize to access the data, and think about the WHAT as the software making that request in behalf of the user.
API Security Defenses
The Basic 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 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 to defend your API server and Mobile App, by building your own Mobile APP Attestation, and you can read in this article section about the overall concept of it, from where I extracted this:
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.
So a Mobile App Attestation will allow your API server to identify, with a very high degree of confidence, that the request is coming from WHAT you expect, the original and unmodified APK you have uploaded to the Google Play store.
THE API SERVER CODE ISSUE
I have tried slim-basic-auth library but it didn't work, I don not know why
I am not familiar at all with the Tuupola project, but from a look into the README.md for the Slim API Skeleton, specially the section for how to get a token and then how to use it. The related code that generates the token can be found at routes/token.php, and to use the token to protect an API route you can find an example at routes/todos.php. This is all configured in the config file config/middleware.php. But I have to say that I am not impressed, security wise, with their posture, and this is because they encourage the exposure of server sensitive data via API endpoints, as we can see at routes/token.php, thus I strongly advise you to immediately delete all this endpoints if they are present in your project.
SUMMARY
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 API server and Mobile App.
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 Obfuscation, JNI/NDK to hide secretes, WAF, UBA, etc.
In the end, the solution to use in order to protect your API server and Mobile App 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
I would strongly recommend you, to also take a look into the 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.
The thing you need is to add a Variable from your client app passing to your server application. Like APP_KEY or CLIENT_ID, which allows your app connecting to the server. You can add encryption so that your server application can only decrypt it and identify the request coming from your client app.
If your app is a web application and hosted in another server, you can implement IP whitelisting in your server.
But if your app is Mobile, you need to pass like a secret_key from mobile to your server.

Implementation concerns regarding IndetityServer4

I have some questions regarding Identityserver4 in the following context:
I have a number of domains (domainA, domainB, domainC ect.) and I’d like all of them to use Identityserver4 for authentication, but I’d like only one implementation of Identityserver4 (with asp.net identity and EF) and have the all domains use this implementation as clients. All domains is in a hosted environment with MS SQL as database, if that has any relevance.
Question 1:
Can IdentityServer4 run in a subfolder/area of domainA, and if so what are the necessary steps for getting this to work, e.g. the endpoints shown in the .well-known endpoint?
Question2:
What are the pitfalls, if any, in hosting Identityserver4 in a subfolder/area under domainA, and also having domainA use Identityserver for authenticating users for the rest of the site, and how to avoid the pitfalls if there are any?
The authorization part that permits one user to do this and not that, and the opposite for another user is not the concern of Identityserver4, but the respective domains/sites own responsibility as I understand what I can find online. In order to make use of roles and roleclaims in asp.net identity core 2 in each domain/site there has to be a user in that domain/site, that has a reference to a user in Identityserver4 in order for the domain to use Identityserver4 for authentication.
Question 3:
How do I avoid that the user must register both on the domain and in Identityserver4, one registration would be preferable and have the other made behind the scenes along with the reference?
I hope someone can provide the answers to one or all of my questions. Links to relevant blogs etc. are welcome, but I have scoured the web to find useful answers without any luck – hopefully some of you have better search engine skills than me.
Q1
Yes you can. IdentityServer is OWIN hosted environment, thus it will be working as a middleware for your domainA, if you set it up so. Having a public endpoint entirely depends on your domainA.
Q2
The possible problem you will possibly encounter would be performance issues. your domainA is going to receive requests from domainB and domainC including, of course, domainA itself. And IdentityServer's checks-up such as authentications, validations, issuing tokens could be obviously time consuming jobs compared to the plain HTTP requests.
While the middleware is doing its job, the performance will hit slightly lower rate then domanB and domainC. But this is a necessary, unavoidable backfire because you added one another layer in your HTTP windows to deal with the authentication / authorization / validation issues on your service endpoints.
You may want to scale out your IdentityServer if the traffic gets much more huger then you expected and you feel your authorization server is dragging the whole services down. I recommend you to perform some stress tests beforehand and compare the performance differences between the services using the identity service and the services using none of that.
Q3
This could be highly opinionated answer. But as you mentioned ASP.NET Identity and EF I think you already know the answer. It seems that you're going to manage the token and identity information in your own hosted DBMS. Then consider it done with the possible duplicated registrations. Your DBMS and your implementation for storing and fetching such data will do it for you as long as you've done it right.
If you're not going to use DBMS for the identity and token data, and use a cache or a file system instead, then you will have to pour some efforts into the implementation in order to guarantee concurrency on the transactions for such data.

How to secure REST API for SPA and Mobile App using Cordova

I've done a lot of research on "best practices" surrounding this and have read blog post after blog post, SO question after SO question, and OWASP article after OWASP article. I've arrived at a few clear answers but some unknowns.
First, the "Do's":
Use JWT for authorizing users on my REST API [1] [2]
Store the JWT in a HTTPOnly/Secure cookie and build in CSRF protection. Do NOT store in HTML5 local storage [3] [4] [5] (Actually, this point is debatable, is it easier to protect against XSS or CSRF? [6])
Verify the signing method of the JWT [7]
Now I started with the assumption that having a SPA (built with Angular) and using HTML5 sessionStorage would be secure enough for short-lived tokens, but there is a point to be made that XSS attacks can happen from a "bad actor" originating in the one of many libraries loaded in from a CDN.
For my specific use case, I do not plan on having long-lived tokens - expiration after 10 minutes of non-use but I'm still figuring out if I want to track expiration by session or use refresh tokens - StormPath recommends the former (no longer stateless?) but I believe big players using JWTs use refresh tokens (Google uses them but states you need to store them in secure, long-term storage which means HTML5 localStorage is again, out of the question).
I would like to make it so my users don't have to log back in if they refresh the page (hence the need to store the token on the client side). I would also like to use my SPA as a "mobile app" with the help of Cordova. The obvious pitfall here is that if I use cookies, there is no baked-in cookie support/storage with Cordova and I'm urged to switch to HTML5 local storage instead. Since on mobile I don't really need to worry about refreshing pages, I can just let my token live in memory and expire with the strategy I settle on.
If I take this approach, cookie-based JWT on Desktop, "Bearer" headers on mobile, I now need an authentication end-point that will give tokens two different ways, and when I authorize on the REST API side, I need to support both cookie-based JWTs (with CSRF) and header based JWT verification. This complication has me worried as I don't know if I can accurately foresee security implications here.
To summarize the barrage of thoughts above:
Create an authentication handler that would hand out tokens via HttpOnly/Secure cookies to desktop, and by payload for mobile.
On my REST API, support both methods of verification - header based and cookie-based - including CSRF protection for the cookie-based approach.
Is there any reason why I wouldn't want to take this approach? I assume if I take XSS on my SPA as a serious risk, then I need a classic login-page for authentication to set the proper cookies because if I do authentication via the SPA, then any XSS attack could potentially intercept that as well (both on mobile and Desktop)! However, on mobile, I'd need to inject the JWT into SPA, maybe through some custom DOM element (meta tag?), but at that point I can just let the SPA perform the login and not consider XSS a threat on mobile devices. Cordova packages all assets into the install package so that's somewhat better but then why not take the same approach on the Desktop version?
My application takes very little user input, it is primarily a dashboard/reporting tool. There will be a "message center" but it's content should always be user-created (by only that user) and sanitized. In my use-case then, would it be ok to deviate from "best practices" and rely on localStorage not counting XSS as a serious risk for my SPA? This would simplify this entire thing (use HTML5 sessionStorage as originally planned) and reduce complexity, which would reduce attack surface for potential security blunders. I just want to make sure I understand the risks before moving forward.
Is there no secure way to make this secure other than by building a native app for mobile and not using Cordova to convert my SPA to a mobile app? I'd hate for this to be the case, but it might very well be.
I'd appreciate all thoughts on the matter!
When thinking of designing javascript based cross-platform applications to run a mobile device, many of the caveats with designing regular web browser based applications do not necessarily apply.
As far as security is concerned, whether you decide to use JWT or simple OAuth tokens, ensure that all your communications are via https.
Please use localStorage as much as you want.
If you consider the anatomy of a http request, all it really is sending some text based message divided into multiple sections to a server. The header of the request is no more secure than any other part of it including the cookies. So the points of interest from a security perspective are generation/validation/invalidation of the token, storage of the token on the device and the transport mechanism of the requests.
Generation/Validation/Invalidation: Generate the tokens on your server. Use some technology/strategy to ensure that there is no possibility for collisions or bleeding. Also, ensure that your strategy will allow you invalidate a token on the server which then subsequently denies access to data requested from the server on further usage of the token. It is then up to you in your app to handle the users UI journey when the server denies access to resources.
How you store the token on the device is constrained to what the device OS make makes available to you. Regarding whether using a native app is better than cross-platform, I think creating a native-cordova plugin to store your token using any specific native strategy if one is unsatisfied with the "out of the box" ones (such as local storage) is possible, although in my experience this is usually overkill. Happy to be corrected on this one if anyone has a different experience.
Please use HTTPS ALWAYS without exception for ALL Webservice end point communications. Is HTTPS foolproof, NO, but you wouldn't build a house without a front door simply because dedicated burglars could learn to pick locks. This secures the transport mechanism considerably.
Usually, this is all native apps have to work with too anyway.

Best practices when configuring relying party for on-premise authorization

I've created a website within the company that utilizes our active directory server to authenticate. I am concerned about security surrounding setting up relying parties with "localhost" domains.
I've pretty much followed this guide on setup. You'll notice about halfway down the page, there is a step to set up the development environment, localhost:44336 as a relying party.
I am concerned that someone could easily get the location of our federation metadata document, and simply roll their own project utilizing the same port and get access to our active directory. Is this a valid concern, or am I worrying over nothing? What would be a better alternative to having to use localhost in this configuration?
Yes it's safe. The metadata document only describes information about endpoints and about the token that active directory is issuing. It doesn't inherently have anything sensitive about it.
The actual authentication is still going to be handled by AD and unless the curious user already has a way to successfully authenticate against your AD then it's rather useless for him to hookup into that document.
Could they potentially create an app that uses your authentication protocol? Sure, but what would be the point if nobody can actually authenticate against it. Allowing this sort of behavior to happen is one of the points of ADFS.

Resources