Authorized Flash Client to Java Server connection - java

I'm building a Flash-based Facebook game with a Java backend, and I'm planning to use a RESTful approach to connect the two of them (not a persistent socket connection). I'm using the AS3 library to connect the client to Facebook, so that's where I have my session information stored. However, how do I authorize client connections back to the server? I can't leave the callback URLs open since that'd let people manipulate game state without playing the game. I need to make sure that the calls are coming from a valid client and through a valid session.
At the moment, users have no direct login to the backend server -- it's all handled through the client frontend. Can I pass the Facebook OAuth2 access token to the backend in a way that the backend can verify its validity? Should that be enough to trust a valid frontend connection?
I could do a two legged OAuth signed request or just use a simple shared secret, but the keys would have to be packed in with the flash client, which makes that almost useless for this use case.
Somebody has to have solved this problem, but I can't find it.

If you are using Java as a backend, I would consider using BlazeDS. It is a great library for doing AMF connections (which are async so fit your non-persistent socket requirement). If you are using Spring on the backend at all, I'd highly recommend using Spring-Flex as well. It adds a bunch of goodies that make exposing AMF services a breeze. Also, it adds hooks to allow 'easy' integration of Spring Security.
For the oAuth stuff, I would move the oAuth portion to the web side instead of the flash client (which I think I understand is what you do now). This way you can authenticate the web session on the server side and secure the page that contains the .swf. Then when your user loads the .swf in your code (assuming you're using spring security integrated into BlazeDS) you can call cs.authenticated on your cs:mx.messaging.ChannelSet. This will work, but may be more reword than you want to do.

We had similar problem in one of our project. What we ended up doing was used the following token passing method:
1) Fresh client connects to the server and get a token that's valid for x amount of time.
2) The client has an obfuscated part of code that uses an algorithm to change the token (and this algorithm changes at some frequency in sync with the server). The client uses the algorithm to change the token and includes it in the next request to the server.
3) The server knows the original token and the algorithm so now it can check to see if the new token in valid and it's from a valid client.
4) The cycle continues.
This is no 100% secure, since someone can really spend time and analyze the communication and eventually understand the pattern, but you can play around with the algorithm so much and change it often enough to make it hard for someone to guess it.
Hope this helps.
P.S. The application that I'm talking about that uses this has been in production for past 5 years and gets ~300k unique users a day and no one has broken in yet.

Related

Rest API security for mobile apps

I'm in the process of designing a mobile application that will need to connect to a server-side process for its business logic and data transactions. I'm writing my server-side code in Java using Spring Boot and I intend to create a Rest API in order for the mobile app to connect to the server.
I'm just doing some research at the moment for the best way to secure the connection between mobile app and server. What I'd like to do is allow the user on the mobile app to log in once they open the app and for them to use the app for as long as they like and for their access to time out after a period of inactivity.
Can anyone recommend any very simple reading on this? I've looked at OAuth2 but that appears to be for logging into web services using another account (like Google, GitHub, etc).
Would it be acceptable to login over https (SSL) by passing username and password to a rest endpoint and returning some sort of token (a GUID?). Then have the client (mobile app) pass that GUID with each subsequent call so the server can verify the call? Is it better to just do everything over SSL in this scenario?
I have done a fair bit of research but I don't seem to be able to find anything that quite matches what I'm trying to do.
Hope someone can help
Thanks
OAUTH2 IS NOT ONLY FOR WEB
Can anyone recommend any very simple reading on this?
I've looked at OAuth2 but that appears to be for logging into web services using another account (like Google, GitHub, etc).
No OAUTH2 is not only for web apps is also for mobile apps and you read this article for a more in depth explanation, but I will leave you with the article introduction:
Like single-page apps, mobile apps also cannot maintain the confidentiality of a client secret. Because of this, mobile apps must also use an OAuth flow that does not require a client secret. The current best practice is to use the Authorization Flow along with launching an external browser, in order to ensure the native app cannot modify the browser window or inspect the contents. If the service supports PKCE, then that adds a layer of security to the mobile and native app flow.
The linked article is very brief, you will need to follow the next chapters to get the full picture.
DO NOT ROLL YOUR OWN AUTHENTICATION / AUTHORIZATION SOLUTION
Would it be acceptable to login over https (SSL) by passing username and password to a rest endpoint and returning some sort of token (a GUID?). Then have the client (mobile app) pass that GUID with each subsequent call so the server can verify the call?
While you can do it I strongly advise you to use an already established OAUTH2 or OPENID connect solution, because they are developed and maintained by experts in the field and battle tested by millions of web and mobile apps using them. This enables to identify ans fix security issues much more quickly that anyone could do in their own in-house solution.
OAuth2
OAuth 2.0 is the industry-standard protocol for authorization. OAuth 2.0 supersedes the work done on the original OAuth protocol created in 2006. OAuth 2.0 focuses on client developer simplicity while providing specific authorization flows for web applications, desktop applications, mobile phones, and living room devices. This specification and its extensions are being developed within the IETF OAuth Working Group.
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.
OpenID Connect performs many of the same tasks as OpenID 2.0, but does so in a way that is API-friendly, and usable by native and mobile applications. OpenID Connect defines optional mechanisms for robust signing and encryption. Whereas integration of OAuth 1.0a and OpenID 2.0 required an extension, in OpenID Connect, OAuth 2.0 capabilities are integrated with the protocol itself.
So for your authentication/authorization needs I would recommend you to go with an OpenID connect solution, that leverages OAuth2 under the hood.
SSL IS ALWAYS NECESSARY?
Is it better to just do everything over SSL in this scenario?
SSL must be always used for everything, http MUST not be used at all in any situation, because once you allow an http request you are vulnerable to a man in the middle attack and I strongly recommend you to read this article from a well know security researcher, Troy Hunt, to see how even a static website must use https and he goes to a great extent to explain why and names very important attack vectors that can harm an application not using https, like WiFi hot-spots hijacking, DNS Hijeacking, Router Exploits, China great cannon, and others.
IMPROVE SSL WITH CERTIFICATE PINNING
Communicating using https is the way to go for any kind of application but developers must be aware that an attacker in control of device where the application is installed can spy https traffic by doing a man in the middle attack with a custom certificate installed in the device the mobiel app is installed, enabling this way for him to understand how the mobile app communicates with the API server in order to mount automated attacks to abuse from same API.
Certificate Pinning
Pinning is the process of associating a host with their expected X509 certificate or public key. Once a certificate or public key is known or seen for a host, the certificate or public key is associated or 'pinned' to the host. If more than one certificate or public key is acceptable, then the program holds a pinset (taking from Jon Larimer and Kenny Root Google I/O talk). In this case, the advertised identity must match one of the elements in the pinset.
You can read this article, with code sample to see how easy is to implement certificate pinning, how it can be difficult to maintain in the operational side, and with a video to see how an attacker can bypass pass certificate pinning in the client side by using Xposed framework.
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.
EDIT:
Nowadays, you can use the Mobile Certificate Pinning Generator to help you with implementing certificate pinning in your mobile app:
That will give you a ready to use pinning configuration for Android and iOS:
RESEARCHING FOR A SOLUTION
Before I point you out to a possible solution I would like to make clear the distinction between 2 concepts that developers frequently are not aware off or take as being the same thing...
The Difference Between WHO and WHAT is Accessing the API Server
The WHO is the user of the mobile app that you can authenticate,authorize and identify in several ways, like using OpenID Connect or OAUTH2 flows.
Now you 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 your genuine mobile app or is a bot, an automated script or an attacker manually poking around your API server with a tool like Postman?
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 and some go the extra mile and compute it at run-time in the mobile app, thus becomes a dynamic secret in opposition to the former approach that is a static secret embedded in the code.
Some Mobile API Security Techniques
I have done a fair bit of research but I don't seem to be able to find anything that quite matches what I'm trying to do.
You can start by read this series of articles about Mobile API Security techniques to understand how Https, Certificate Pinning, APi Keys, HMAC, OAuth2 and other techniques can be used to protect the communication channel between your mobile app and the API serve, and how they can be bypassed.
To solve the problem of WHAT is accessing your mobile app you need to use one or all the solutions mentioned in the series of articles about Mobile API Security Techniques that I mentioned above and accepted that they can only make unauthorized access to your API server harder to bypass but not impossible.
A better solution can be employed by using a Mobile App Attestation solution that will enable the API server to know is receiving only requests from a genuine mobile app.
A POSSIBLE BETTER SOLUTION
The use of a Mobile App Attestation solution will enable the API server to know WHAT is sending the requests, thus allowing to respond only to requests from a genuine mobile app while rejecting all other requests from unsafe sources.
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.
This is a positive model where false positives do not occur, thus the API server is able to deny requests with the confidence of not blocking legit users of your mobile app.
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
Properly securing a mobile app and the API server is a task composed of several layers of defense that you must put together in order to protect it.
How many layers to use will depend on the data your are protecting, the value it have for the business, the damage it can cause when leaked in a data breach and how much you may be penalized by law enforcement, like GDPR in Europe.
What I usually do is crafting a JSON web token (https://jwt.io/), and handle the sessions on my own.
JWT is really nice, since you only need to define a secret key on the server side. As long as your clients are able to pass the string you crafted (inside the headers for example), and as long as nobody gets to retrieve your secret key, you are sure that every data you push when creating the token was generated by you. (Don't hesitate to use the strongest encryption algorithm)
For a secure connection use HTTPS at level TLS 1.2 level. Then pin the server certificate in the app, that will prevent MITM attacks.
It is safe to pass the user name and password. You can return a time-limited token for further authentication is needed/desired.
With HTTPS everything but the address portion of the URL is encrypted. But be careful with the query string, it may end up in the server logs.
Thanks again for these replies. I've been implementing my service to run under https by using server.ssl.key-store parameters and it looks like it's working okay. I have used keytool.exe to create a trust store and I run my SpringBoot app (with Tomcat embedded) using that trust store. I can open a browser to my REST endpoint (using https this time, not http), the browser asks for authentication and when I enter my user details, it matches them against my db user and allows me to see the response from the server.
One question though, what's the point of having a trust store on the server side (Java) if I can just access the REST endpoint using any old browser and just enter my user name and password? Eventually, this REST endpoint won't be accessed via a browser, it'll be accessed using a mobile app programmatically, so I assume I'll be logging on using that with username and password over https. I thought I'd need to have a certificate of some sort on the client side in order to communicate or does it not work like this?
Thanks again

Authentication mechansim for java game client / mysql db

I need to figure out how to best authenticate users which are connecting from a C++ game client, against a mySQL database on another server, and I plan on writing a java web service to accomplish this.
Security is of primary concern, I need to make sure that the data flowing across the wire is encrypted, so I'll be leveraging SSL (originally I thought about message level encryption using ws-security however I think it's too much overhead).
What I really need to figure out is what kind of authentication mechanism I should provide. These users will be supplying usernames and passwords, and will be issuing a web request to a service.
I haven't decided whether the service should be a traditional SOAP web service or a RESTful one. The whole idea behind rest is to make the server stateless, and since the client will basically be establishing a session with the service, I don't see a point in using REST here.
Having said all that, what I really need to nail down is how exactly to perform the handshake and how to persist the session.
Are there any popular frameworks out there that provide APIs to do this against a mySQL database?
Again the client will offer up a UN / PW to the server, which needs to decrypt them (SSL should take care of that), authenticate them against the account info stored in a mysql DB, and then return some kind of hash or something similar so that the user's session can persist or the user doesn't have to log in anymore to issue additional requests.
Could anyone recommend a framework / some reading material for me to glance over?
Keep things as simple as possible.
HTTP is already stateless, and the idea of a login followed by a continued session is well established (session cookie). Use this paradigm and you won't have any troubles.
You also get the benefit of a very light-weight and open communication protocol and many good libraries for easy serialization / deserialization of common REST payloads like JSON or XML.
REST also means that you can use the same server with other clients quite easily.
I'd take a look at oauth:
http://developers.sun.com/identity/reference/techart/restwebservices.html
A well established pattern is:
1. log in & receive an oauth token
2. store token in db with user's internal id (and any other data such as token expiration time you wish to store).
3. send token to client, client persists token
4. client sends token for all future requests
5. server fetches user info from token
This method should work well with any client language and any backend datastore.
I would recommend to use REST. As authorization framework you can use standard container's jdbc or file realms on JAAS. If login/password pair is successful, store them at client side. After that, you can perform requests with auth credential supplied per request. I used jersey client for this. For [de]serialization from/to XML/json XStream library "do all dat math". Have a nice day.

How to secure a REST web service in Java EE 6

I have made a web application using Java EE 6 (using reference implementations) and I want to expose it as a REST web service.
The background is that I want to be able to retrieve data from the web application to a iOS app I made. The question is how would I secure the application? I only want my application to use the web service. Is that possible and how would I do this? I only need to know what I should search for and read and not the actual code.
Unfortunately, your webservice will never be completely secure but here are few of the basic things you can do:
Use SSL
Wrap all your (app) outbound payloads in POST requests. This will prevent casual snooping to find out how your webservice works (in order to reverse engineer the protocol).
Somehow validate your app's users. Ideally this will involve OAUTH for example using Google credentials, but you get the idea.
Now I'm going to point out why this won't be completely secure:
If someone gets a hold of your app and reverse engineers it, everything you just did is out the window. The only thing that will hold is your user validation.
Embedding a client certificate (as other people have pointed out) does nothing to help you in this scenario. If I just reverse enginneered your app, I also have your client certificate.
What can you do?
Validate the accounts on your backend and monitor them for anomalous usage.
Of course this all goes out the window when someone comes along, reverse engineers your app, builds another one to mimic it, and you wouldn't (generally) know any better. These are all just points to keep in mind.
Edit: Also, if it wasn't already obvious, use POST (or GET) requests for all app queries (to your server). This, combined with the SSL should thwart your casual snoopers.
Edit2: Seems as if I'm wrong re: POST being more secure than GET. This answer was quite useful in pointing that out. So I suppose you can use GET or POST interchangeably here.
Depends on how secure you want to make it.
If you don't really care, just embed a secret word in your application and include in all the requests.
If you care a little more do the above and only expose the service via https.
If you want it to be secure, issue a client certificate to your app and require a
valid client certificate to be present when the service is accessed.
my suggestions are:
use https instead of http. there are free ssl certificate avaliable,
get one and install.
use a complex path such as 4324234AA_fdfsaf/ as the root end point.
due to the nature of http protocol, the path part is encrypted in the https request. therefore it's very safe. there are ways to decrypt the request through man-in-the-middle attack but it requires full control over the client device including install an ilegal ssl certificate. but, i'd spend more time on my app to make it successful.
Create a rule on the machine which hosts your Web Service to only allow your application to access it through some port. In Amazon EC2, this is done creating a rule in the instance Security Group.
We have used RestEasy as a part to securing our exposed RESTful webservices. There should be lot of example out there but here is the one which might get you started.
http://howtodoinjava.com/2013/06/26/jax-rs-resteasy-basic-authentication-and-authorization-tutorial/
You can also use OAUTH:
http://oltu.apache.org/index.html

Securing a REST API

I am in the middle of developing a PHP social media web application which will be supported by various web services each operating a REST API. Web services will probably be implemented in Java with MySQL data layer but the whole point of what I am trying to do is make it really easy to implement modules in different languages/data stores depending on what is approriate.
So for example when the user logs into the application via a login form the PHP code connects to a web service and POSTs the username and password to check if they should be authenticated. I would normally at this point start a session and store it in a session data store.
Another example could be if a user sends a private message to another user. The message would be POSTed to the private messaging web service which would take care of all the storage. Similarly the web service could be contacted to retrieve messages for a user.
Although I understand how to implement the REST web service in Java and make the connection to it in PHP I am totally unsure as to how to secure the data being passed and make sure that it is the users data being returned. If for example I want to get all of user As private messages how does the web service know to return that users. I could pass that users identifier as part of the GET url but then surely any old user could just figure out the GET url and use it to look up other peoples messages. I thought maybe I could pass over the session identifier and IP address which would allow me to check the session data store and make sure it is the correct user?
To secure the data that is important - like the username/password I thought I would just pass it over SSL.
Hope this explains my problem better.
Thanks
Take a look at HTTP Digest authentication. Most clients should support it, and it means the auth details can be passed securely with each request as part of the headers without interfering with the payload of the request itself.
I think requiring OAuth is a good choice. Your end users should appreciate that other websites don't need to ask usernames and passwords to access their data. As far as SSL, it's clearly worth doing if you can. You'll have to see if the performance trade-off is acceptable.
Keep in mind that your api must mimic the HTTP protocol.
Http is stateless, and by adding any Sessions or so, you're trying to fake an "Alwaysconnected" method.
With a LoginForm, it's like I'll have to send two requests for each calls ;)
These are basically 2 questions.
When privacy is a concern I'd go for the safest option: Serve data over SSL (via HTTPS).
As far as authentication is concerned, there are several possibilities. Basic over SSL is one of them, but a simple login form with a cookie can be another one. (ASP.Net Forms Authentication for example.) This all depends on how you want to implement your authentication mechanism.

Secure connection between client and server

I'm developing a server component that will serve requests for a embedded client, which is also under my control.
Right now everything is beta and the security works like this:
client sends username / password over https.
server returns access token.
client makes further requests over http with the access token in a custom header.
This is fine for a demo, but it has some problems that need to be fixed before releasing it:
Anyone can copy a login request, re-send it and get an access token back. As some users replied this is not an issue since it goes over https. My mistake.
Anyone can listen and get an access key just by inspecting the request headers.
I can think of a symmetric key encryption, with a timestamp so I can reject duplicate requests, but I was wondering if there are some well known good practices for this scenario (that seems a pretty common).
Thanks a lot for the insight.
PS: I'm using Java for the server and the client is coded in C++, just in case.
I don't get the first part, If the login request is https, how can anyone just copy it?
Regarding the second part, t This is a pretty standard session hijacking scenario. See this question. Of course you don't have the built-in browser options here, but the basic idea is the same - either send the token only over a secure connection when it matters, or in some way associate the token with the sending device.
In a browser, basically all you have is IP address (which isn't very good), but in your case you may be able to express something specific about your device that you validate against the request to ensure the same token isn't being used from somewhere else.
Edit: You could just be lucky here and be able to rule out the IP address changing behind proxies, and actually use it for this purpose.
But at the end of the day, it is much more secure to use https from a well-known and reviewed library rather than trying to roll your own here. I realize that https is an overhead, but rolling your own has big risks around missing obvious things that an attacker can exploit.
First question, just to get it out there: if you're concerned enough about nefarious client-impersonator accesses, why not carry out the entire conversation over HTTPS? Is the minimal performance hit significant enough for this application that it's not worth the added layer of security?
Second, how can someone replay the login request? If I'm not mistaken, that's taking place over HTTPS; if the connection is set up correctly, HTTPS prevents replay attacks using one-time nonces (see here).
One of the common recommendations is - use https
https man in the middle attack aside using https for the entire session should be reliable enough. You do not even need to worry about access tokens - https takes care of this for you.
Using http for further requests seems to introduce some vulnerabilities. Now anybody with a network sniffer can intercept your traffic steal the token and spoof your requests. you can build protection to prevent it - token encryption, use once tokens, etc. but in doing so you will be re-creating https.
Going back to the https man in the middle attack - it is based on somebody's ability to insert himself between your server and your client and funnel your requests through their code. It is all doable i.e. in case the attacker has access to the physical network. The problem such attacker will face is that he will not be able to give you a proper digital certificat - he does not have the private key you used to sign it. When https is accessed through a browser, the browser gives you a warning but still can let you through to the page.
In your case it is your client who will communicate with the server. And you can make sure that all proper validations of the certificate are in place. If you do that you should be fine
Edit
Seconding Yishai - yes some overhead is involved, primarily CPU, but if this additional overhead pushes your server over board, you have bigger problems with your app

Categories