Securing Grails REST service for use with mobile applications - security

I am busy doing some research into using REST services with mobile applications and would appreciate some insight. The scenario is as follows.
Consider a web application that provides a service to users. The web application will also be the main interaction point for the users. This will be done in Grails, and secured with Spring Security.
Now, we want to provide a REST service so that users can use the service via mobile applications. Since Grails has such nice support for making the existing web application RESTful, we will use the built-in Grails support for that.
My question now is, what would be the "best" way to secure the REST service interface so that it can be use from mobile applications (native- iOS, Andriod, WM7, BB).
The information exchanged are highly sensitive, so the more secure, the better.
Thanks

We decided to split our grails project in three...
model-domain-project (This is the "admin" section with all the views/controller scaffolded, and all the services, domain)
web-app (this is the main application, controllers, views)
api-rest-app (this is the rest controllers)
The model-domain-project is a plugin that it's plugged in the web-app and the api-app, contains the domain model, services, and all the database security, transactions, etc.
The web-app is all the html templates, views and controllers, here we are using the attributes of Spring Security
The api-rest-app we are using grails-filters and we are using Basic-Authorization via https with a token with an expiration date...
if the expiration date of the token is reached you will have to ask for another token with a "request-token" we sent you with the first token... (it's more or less like oauth2)
To get the two first tokens, you will have to confirm the device via a login with user/phone/password then you receive a key via sms that you will have to enter in the app
Do not know if this the best way, but it's the way we do it...
Sometimes we are using the web-app as client and call the api-rest-app...

Related

Ways for verify mobile application client on server

I'm looking for a way to design
Mobile APP <--> Server API which:
authorize user and app for work with server using OAuth2.0
validate on server, that it's legitimate application
Problem I face now: Application in Oauth2.0 terminology is a public clients:
there is no way to secure any static information in application bundle - any one can extract such info and reuse it in fake application.
And if I add some additional method for register new instance of application on Server - there is nothing stop fake application from doing the same thing.
Is there ANY way to exchange data between Application and Server without involving REST API, or get verified information aboute calling application.
I know that answer is platform specific - I'm interesting in information on any platform as I can search analog for others.
For mobile apps use Authorization Code Flow (PKCE) which generates a runtime secret, so that there's no need for a fixed one to be deployed with the app.
A rogue app can potentially use the Client Id and Redirect URI of your app, but one way to deal with that is to use Claimed HTTPS Scheme Based Redirects, as recommended in Financial Grade APIs / Native Apps.
If interested in this approach, my blog has a couple of detailed examples:
Android AppAuth Claimed HTTPS Scheme Code Sample
iOS AppAuth Claimed HTTPS Scheme Code Sample
The Difference Between WHO and WHAT is Accessing the API Server
I'm looking for a way to design
Mobile APP <--> Server API which:
authorize user and app for work with server using OAuth2.0 <--- WHO
validate on server, that it's legitimate application <--- WHAT
Before I dive into your questions I would like to first clear a misconception that I usually find among developers of any seniority, that is about the difference between who and what is accessing an API server
I wrote a series of articles around API and Mobile security, and in the article Why Does Your Mobile App Need An Api Key? you can read in detail the difference between who and what is accessing your API server, but I will extract here the main takes from it:
The what is the thing making the request to the API server. Is it really a genuine instance of your mobile app, or is it a bot, an automated script or an attacker manually poking around your API server with a tool like Postman?
The who is the user of the mobile app that we can authenticate, authorize and identify in several ways, like using OpenID Connect or OAUTH2 flows.
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.
So, you need to bear in mind that the guarantee that you know who is in the request cannot guarantee you that the request comes indeed from what your API server expects, a genuine and unmodified version of your mobile app.
Possible Solution
And if I add some additional method for register new instance of application on Server - there is nothing stop fake application from doing the same thing.
Is there ANY way to exchange data between Application and Server without involving REST API, or get verified information aboute calling application.
If your API server can have a high degree of confidence that the request are indeed from what it expects, a genuine and unmodified version of you mobile app then registering a new instance of the application and exchanging data with the API server can be done with the confidence that a bad actor is not involved.
You can resort to UBA and RASP solutions to help you with knowing what is making the API requests:
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.
RASP:
Runtime application self-protection (RASP) is a security technology that uses runtime instrumentation to detect and block computer attacks by taking advantage of information from inside the running software.
RASP technology is said to improve the security of software by monitoring its inputs, and blocking those that could allow attacks, while protecting the runtime environment from unwanted changes and tampering.
UBA is based on negative identification models that do 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. The UBA solution is based on analyzing each API request and they don't have client side realtime intelligence gathering from whats going on the mobile app and its device.
RASP solutions are client side, and the API server has no visibility for what they are detecting and blocking. Once they are client side they can be bypassed without the API server know it happened, therefore it will accept the API requests from this bypass.
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.
So, the possible better solution section in the linked answer mentions the use of a Mobile App Attestation solution that will combine realtime background communication between a cloud service and the mobile app to attest the mobile app is genuine and unmodified, and that is running in a trusted device. The API server will then be able to know with a very high degree of confidence that what is making the request is indeed a genuine and unmodified version of the mobile app running in a trusted device.
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.

What is the best Security Implementation for WebApi and Web Applications

I'm trying to create a web application that uses a Web API to perform database operations. I've created a project at work that uses Windows Authentication on the API Level. Since this is an intranet web application I don't need to implement a login mechanism on the web application. However, this project I'm working on can be private or public web application and I would like to implement a login mechanism but I would like to be able to specify what type of security to use i.e. LDAP, generic username/password, Google, Facebook, etc.
The question is, what is the best strategy to implement security on both Web Application and Web Api. For Web Api, I could probably implement some soft of token mechanism like other Apis. But not sure if there are other ways.
Is Sign-in option like Google, Facebook, etc done on the Front-end side? or can I Implement it on the WebApi side?
The best practice on this case,
Web Application: client certificate authentication or username/password
Web API: JWT
or if the target company uses G suits with the company domain, Google will be okay.
You can set a filter using domain name of the email address.

How do I secure a REST-API?

I've set up an API with authentication but I want to only allow certain applications and websites to access it. What do I do?
I've got authentication set up for users that are Logged in only being able to access the API, however, how do I prevent them from just logging in from anywhere?
Before I address your question, I think is important that first we clear a common misconception among developers, regarding WHO and WHAT is accessing an API.
THE DIFFERENCE BETWEEN WHO AND WHAT IS COMMUNICATING WITH YOUR API SERVER
To better understand the differences between the WHO and the WHAT are accessing your mobile app, let’s use this picture:
The Intended Communication Channel represents your mobile being used as you expected, by a legit user without any malicious intentions, using an untampered version of your mobile app, and communicating directly with your API server without being man in the middle attacked.
The actual channel may represent several different scenarios, like a legit user with malicious intentions that may be using a repackaged version of your mobile app, a hacker using the genuine version of you mobile app while man in the middle attacking it to understand how the communication between the mobile app and the API server is being done in order to be able to automate attacks against your API. Many other scenarios are possible, but we will not enumerate each one here.
I hope that by now you may already have a clue why the WHO and the WHAT are not the same, but if not it will become clear in a moment.
The WHO is the user of the mobile app that we can authenticate, authorize and identify in several ways, like using OpenID Connect or OAUTH2 flows.
OAUTH
Generally, OAuth provides to clients a "secure delegated access" to server resources on behalf of a resource owner. It specifies a process for resource owners to authorize third-party access to their server resources without sharing their credentials. Designed specifically to work with Hypertext Transfer Protocol (HTTP), OAuth essentially allows access tokens to be issued to third-party clients by an authorization server, with the approval of the resource owner. The third party then uses the access token to access the protected resources hosted by the resource server.
OpenID Connect
OpenID Connect 1.0 is a simple identity layer on top of the OAuth 2.0 protocol. It allows Clients to verify the identity of the End-User based on the authentication performed by an Authorization Server, as well as to obtain basic profile information about the End-User in an interoperable and REST-like manner.
While user authentication may let your API server know WHO is using the API, it cannot guarantee that the requests have originated from WHAT you expect, your mobile app.
Now we need a way to identify WHAT is calling your API server, and here things become more tricky than most developers may think. The WHAT is the thing making the request to the API server. Is it really a genuine instance of your mobile app, or is a bot, an automated script or an attacker manually poking around your API server with a tool like Postman?
For your surprise you may end up discovering that It can be one of your legit users using a repackaged version of your mobile app or an automated script trying to gamify and take advantage of your service.
Well, to identify the WHAT, developers tend to resort to an API key that usually they hard-code in the code of their mobile app. Some developers go the extra mile and compute the key at run-time in the mobile app, thus it becomes a runtime secret as opposed to the former approach when a static secret is embedded in the code.
The above write-up was extracted from an article I wrote, entitled WHY DOES YOUR MOBILE APP NEED AN API KEY?, and that you can read in full here, that is the first article in a series of articles about API keys.
YOUR QUESTIONS
I've got authentication set up for users that are Logged in only being able to access the API, however, how do I prevent them from just logging in from anywhere?
If by logging in from anywhere you mean any physical location, then you can use blocking by IP address as already suggested by #hanshenrik, but if you mean blocking from logging from other applications, that are not the ones you have issued the API keys for, then you have a very hard problem in your hands to solve, that leads to your first question:
I've set up an API with authentication but I want to only allow certain applications and websites to access it. What do I do?
This will depend if WHAT is accessing the API is a web or a mobile application.
Web application
In a web app we only need to inspect the source code with the browser dev tools or by right click on view page source and search for the API key, and then use it in any tool, like Postman or in any kind of automation we want, just by replicating the calls as we saw them being made in the network tab of the browser.
For an API serving a web app you can employ several layers of dense, starting with reCaptcha V3, followed by Web Application Firewall(WAF) and finally if you can afford it a User Behavior Analytics(UBA) solution.
Google reCAPTCHA V3:
reCAPTCHA is a free service that protects your website from spam and abuse. reCAPTCHA uses an advanced risk analysis engine and adaptive challenges to keep automated software from engaging in abusive activities on your site. It does this while letting your valid users pass through with ease.
...helps you detect abusive traffic on your website without any user friction. It returns a score based on the interactions with your website and provides you more flexibility to take appropriate actions.
WAF - Web Application Firewall:
A web application firewall (or WAF) filters, monitors, and blocks HTTP traffic to and from a web application. A WAF is differentiated from a regular firewall in that a WAF is able to filter the content of specific web applications while regular firewalls serve as a safety gate between servers. By inspecting HTTP traffic, it can prevent attacks stemming from web application security flaws, such as SQL injection, cross-site scripting (XSS), file inclusion, and security misconfigurations.
UBA - User Behavior Analytics:
User behavior analytics (UBA) as defined by Gartner is a cybersecurity process about detection of insider threats, targeted attacks, and financial fraud. UBA solutions look at patterns of human behavior, and then apply algorithms and statistical analysis to detect meaningful anomalies from those patterns—anomalies that indicate potential threats. Instead of tracking devices or security events, UBA tracks a system's users. Big data platforms like Apache Hadoop are increasing UBA functionality by allowing them to analyze petabytes worth of data to detect insider threats and advanced persistent threats.
All this solutions work based on a negative identification model, by other words they try their best to differentiate the bad from the good by identifying WHAT is bad, not WHAT is good, thus they are prone to false positives, despite of the advanced technology used by some of them, like machine learning and artificial intelligence.
So you may find yourself more often than not in having to relax how you block the access to the API server in order to not affect the good users. This also means that this solutions require constant monitoring to validate that the false positives are not blocking your legit users and that at same time they are properly keeping at bay the unauthorized ones.
Mobile Application
From your reply to a comment:
What about for mobile applications?
Some may think that once a mobile app is released in a binary format that their API key will be safe, but turns out that is not true, and extracting it from a binary is sometimes almost as easy as extracting it from a web application.
Reverse engineering a mobile app is made easy by plethora of open source tools, like the Mobile Security Framework(MobSF), Frida, XPosed, MitmProxy, and many other more, but as you can see in this article, it can be done with MobSF or with the strings utility that is installed in a normal Linux distribution.
Mobile Security Framework
Mobile Security Framework is an automated, all-in-one mobile application (Android/iOS/Windows) pen-testing framework capable of performing static analysis, dynamic analysis, malware analysis and web API testing.
Frida
Inject your own scripts into black box processes. Hook any function, spy on crypto APIs or trace private application code, no source code needed. Edit, hit save, and instantly see the results. All without compilation steps or program restarts.
xPosed
Xposed is a framework for modules that can change the behavior of the system and apps without touching any APKs. That's great because it means that modules can work for different versions and even ROMs without any changes (as long as the original code was not changed too much). It's also easy to undo.
MiTM Proxy
An interactive TLS-capable intercepting HTTP proxy for penetration testers and software developers.
Regarding APIs serving mobile apps a positive identification model can be used by using a Mobile App Attestation solution that guarantees to the API server that WHAT is making the requests can be trusted, without the possibility of false positives.
The Mobile App Attestation
The role of a Mobile App Attestation service is to guarantee at run-time that your mobile app was not tampered or is not running in a rooted device by running a SDK in the background that will communicate with a service running in the cloud to attest the integrity of the mobile app and device is running on.
On successful attestation of the mobile app integrity a short time lived JWT token is issued and signed with a secret that only the API server and the Mobile App Attestation service in the cloud are aware. In the case of failure on the mobile app attestation the JWT token is signed with a secret that the API server does not know.
Now the App must sent with every API call the JWT token in the headers of the request. This will allow the API server to only serve requests when it can verify the signature and expiration time in the JWT token and refuse them when it fails the verification.
Once the secret used by the Mobile App Attestation service is not known by the mobile app, is not possible to reverse engineer it at run-time even when the App is tampered, running in a rooted device or communicating over a connection that is being the target of a Man in the Middle Attack.
The Mobile App Attestation service already exists as a SAAS solution at Approov(I work here) that provides SDKs for several platforms, including iOS, Android, React Native and others. The integration will also need a small check in the API server code to verify the JWT token issued by the cloud service. This check is necessary for the API server to be able to decide what requests to serve and what ones to deny.
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.
So using API keys may sound like locking the door of your home and leave the key under the mat, but not using them is liking leaving your car parked with the door closed, but the key in the ignition.

Is it a good practice to separate the authentication server from the resource server?

As with many applications, my service's authentication logic lives in the application code. Now however, I need to expand my authentication to incorporate 3rd party identity providers for single sign on.
I want to retain the old authentication behavior (database lookup) but also want to add support for 3rd party identity providers.
With this increase in complexity, does it make sense to separate the authentication logic to its own service? In this model the application server will redirect unauthenticated users to the authentication server. After authentication is successful, the authentication server will redirect back to the application server.
Is this approach sound?
If you have available servers and infrastructure budget, let your web application perform the authentication, using a community maintained library.
Generally its no recommended to build one by yourself.
Store your users in a database table.
Authentication using other sites problems:
Your visitor may not want to have an account with 3rd party site.
It results in giving too much information to the 3rd party site (who share much of it with other sites which use their authentication mechanism).
It is generally a good idea to separate your authentication logic and have a different service perform that task. This is also true for other 'cross cutting' concerns such as authorization and SSL offloading. It gives you a simpler development environment and in general an app that is easier to reason about (for example, you don't have to worry about authentication while in development mode and you can develop the services independently which goes a long way in terms of productivity and velocity).
In order to compose the authentication service with your application, it is better to have a third component that orchestrates and routes the calls accordingly (as opposed to having autentication related code in your application).

Authentication for mobile web applications

I am new to mobile web programming - having spent a lot of time designing back end Windows services and some IOS native programming recently.
We are in the process of designing a new app for usage by our end clients. We need it to be light weight, responsive and also work on all mobile devices - IOS, Android and Win 8. After much research we have narrowed down to using HTML 5 based JS framework - namely either Chocolate Chip UI or Phone JS. Server side code is PHP.
I have a question about the best practices for authentication when it comes to mobile Web applications and sites
We could present the login form with user details and post to server/authenticate and write to an authentication cookie and then redirect to an HTML 5 page from which point on all data GET and POST is using REST Calls.
Or not post to server but authenticate using a service and store an authenticated token or cookie and check when requesting/posting data.
But are the above methods still relevant - since i have never had to deal with UI authentication before - what are the best methodologies when designing mobile web apps specially with regards to authentication?
Im my JAVA EE projects, I'm using a JDBC Realm for storing users, passwords and roles and JAVA EE build-in Container Managed Security for securing my webpages bases on the roles. If a user is not authenticated a Form will be shown where he or she has to enter the security information. The web pages get data access by services with CRUD functionality.
For Android, Java FX, WPF and so on I'm using a Restful Interface wrapping the Java specific service to support different programming languages combined with OAuth2 (http://oauth.net/2/). A few benefits of OAuth2 are that no user name and password must be stored on the client side, the obtained token can be refreshed and you could seperate parts of your services by using scopes (read-only, full, only calender access,...) befined by yourself. The tokens must be stored in a database and mapped to the user principal it belongs to if a REST service will be accessed. Your users can be also allowed to register own third-party applications using specific scopes of the REST interface.
Herr is an example implementation: https://github.com/OpenConextApps/apis/blob/master/README.md and here some information about JAVA EE security: http://docs.oracle.com/javaee/7/tutorial/doc/security-webtier.htm#BNCAS

Resources