We are building a mobile application and its API server with architecture as in the picture below.
We have WSO2 as the API gateway in front of the Spring Boot API Server. We use WSO2 API Manager to restrict who can call the APIs. Only clients that have registered with our WSO2 and have the correct consumer key and secret can call an API through WSO2, by which the client first call to WSO2's token endpoint to exchange the consumer key and secret with an access token, then call the desired API with the access token in header Authorization: Bearer <access token>
We have a problem that we don't know how to keep the consumer secret since security audits prohibit us to store the secret in mobile app installer package.
There were some questions already asked such as
WSO2 API Manager - How does mobile app connect to API Manager?
WSO2 Api Manager OAuth2 DCR security in public native mobile app
But no answers correctly point to the problem. Most of them was mislead by the complexity of oauth2 flow.
To make the problem specific and clear, please assume that our mobile don't have users to login. The goal of this problem is to allow only trusted mobile application to call the API through WSO2.
Please help suggest if this is possible or not. Or we have no choice but to allow anyone to call the API. Or WSO2' consumer subscribtion feature is not designed to be used directly from mobile app at all?
After doing some research, I found 2 options people usually do.
Separate APIs into 2 groups. First group contains APIs that need to be used without user login, such as API to get initialization data or to get data for landing page of the app. Thease APIs are set as public, allow anyone to call without clientId and secret. The seconds group contains secured APIs that required the token. Mobile app can use Oauth2 PKCE flow to exchange the token with user identity proof.
Obfuscate clientId and secret and keep them in mobile app installer package. The APIs are still be separated into 2 groups as before. But the first group requires client-level token (oauth2 client credential type) and the second group requires user-level token (resource owner password or authorization code type)
I prefer option 2. In my opinion, I think the first option does not really make sense. People choosing this option, maybe, just do it to bypass the security audit check list, to not store the secret in public client, without really concern about security problem. It's like when you cannot trust your kids to keep a key to your house safely, so you decided to remove the lock from the door.
Having every APIs protected and keep the key in the client. Even though some hacker can manage to find the secret, he can only hack APIs of the first group and you can track the clientId he used. You know the expect behavior of the client so it is easy to setup an alarm that detect malicious activities from the client and revoke the token, reset the secret and rollout more complex obfuscation algorithm.
You may want to read OAuth 2.0 for Native Apps [RFC7636] spec. It states:
Public native app clients MUST implement the Proof Key for Code
Exchange (PKCE [RFC7636]) extension to OAuth, and authorization
servers MUST support PKCE for such clients, for the reasons detailed
in Section 8.1.
Check the below answer too.
How to implement Oauth2 without sending client_secret in WSO2 APIM
I am developing a REST API secured via OAuth2 with Spring that will be used from an Android application (the client). In order to access any endpoint of my API, a OAuth2 access token is required and handed over to the endpoint via Authorization Header in a way similar to this:
"Authorization" - "Bearer accesstokenhere"
In order to acquire an access token, a username and password must be provided, as well as a client ID and client secret (they represent the Android app). The clientID and client secret are handed over to the token endpoint via Authorization Header in a way similar to this, which is specified by Spring:
"Authorization" - "Basic clientId:clientSecret"
If the client ID and client secret match a client defined on the server and if the user exists and the password is correct, access token and refresh token are returned.
Now my question is how I can securely store my clientId and client secret inside the Android application, making sure someone who reverse engineers my app does not get access to them?
Also, if I were to develop an iOS application (a second client), would it be wise to use a different clientID and client secret from a security POV?
You can't - even if there was a way, I could still just inspect the payload on the wire to determine the values. See section 8.5 of the OAuth 2.0 for Native Apps
Secrets that are statically included as part of an app distributed to multiple users should not be treated as confidential secrets, as one user may inspect their copy and learn the shared secret. For this reason, and those stated in Section 5.3.1 of [RFC6819], it is NOT RECOMMENDED for authorization servers to require client authentication of public native apps clients using a shared secret, as this serves little value beyond client identification which is
already provided by the "client_id" request parameter.
Your client id/secret parameters are just providing the identity of application making the request, as such it is recommended you'd want to create a different client for your iOS application, both from a security isolation point of view + for any analytics you want to gather about use of your application (e.g. 'how many sign in attempts are you retrieving by client id?' etc)
However, a threat actor could reverse engineer your settings, take your client id + secret and then start hitting your token endpoint with a username/password combo to attempt to brute force your application. If an endpoint accepts these values and returns a success/failure code, this is a useful attack vector for someone trying to compromise your system.
The current recommended approach is to use the 'Authorization code flow'
The best current practice for authorizing users in native apps is to
perform the OAuth authorization request in an external user-agent (typically the browser), rather than an embedded user-agent (such as one implemented with web-views).
Previously it was common for native apps to use embedded
user-agents (commonly implemented with web-views) for OAuth
authorization requests. That approach has many drawbacks,
including the host app being able to copy user credentials and
cookies, and the user needing to authenticate from scratch in each
app. See Section 8.12 for a deeper analysis of using embedded
user-agents for OAuth."
Have a look at AppAuth for Android for more information,
Android's AccountManager appears to fetch the same cached auth token for apps with different UIDs - is this secure? It does not seem compatible with OAuth2, since access tokens are not supposed to be shared between different clients.
Background/Context
I am building an Android app which uses OAuth2 for authentication/authorization of REST API requests to my server, which is an OAuth2 provider. Since the app is the "official" app (as opposed to a 3rd-party app), it is considered a trusted OAuth2 client, so I am using the resource owner password flow for obtaining an OAuth2 token: the user (the resource owner) enters his username/password into the app, which then sends its client ID and client secret along with the user credentials to my server's OAuth2 token endpoint in exchange for an access token that can be used to make API calls, as well as a long-lived refresh token used to get new access tokens when they expire. The rationale is that it is more secure to store the refresh token on the device than the user's password.
I am utilizing AccountManager for managing the account and associated access token on the device. Since I am providing my own OAuth2 provider, I have created my own custom account type by extending AbstractAccountAuthenticator and other required components, as explained in this Android Dev Guide and demonstrated in the SampleSyncAdapter sample project. I am able to successfully add accounts of my custom type from within my app and manage them from the "Accounts and sync" Android settings screen.
The Issue
However, I am concerned with the way the AccountManager caches and issues auth tokens - specifically, that the same auth token for a given account type and token type seems to be accessible by any app to which the user has granted access.
To obtain an auth token through the AccountManager, one must invoke AccountManager.getAuthToken(), passing, among other things, the Account instance for which to obtain the auth token and the desired authTokenType. If an auth token exists for the specified account and authTokenType, and if the user grants access (via the grant "Access Request" screen) to the app which has made the auth token request (in such cases where the requesting app's UID does not match the authenticator's UID), then the token is returned. In case my explanation is lacking, this helpful blog entry explains it very clearly. Based on that post, and after examining the source of AccountManager and AccountManagerService (an internal class which does the heavy lifting for AccountManager) for myself, it appears that only 1 auth token is stored per authTokenType/account combo.
So, it seems feasible that if a malicious app knew the account type and authTokenType(s) used by my authenticator, it could invoke AccountManager.getAuthToken() to obtain access my app's stored OAuth2 token, assuming that the user grants access to the malicious app.
To me, the problem is that AccountManager's default caching implementation is built on a paradigm on which, if we were to layer an OAuth2 authentication/authorization context, it would consider the phone/device to be a single OAuth2 client for a service/resource provider. Whereas, the paradigm that makes sense to me is that each app/UID should be considered as its own OAuth2 client. When my OAuth2 provider issues an access token, it is issuing an access token for that particular app which has sent the correct client ID and client secret, not all apps on the device. For instance, the user might have both my official app (call it app Client A), and a "licensed" third-party app which uses my API (call it app Client B) installed. For the official Client A, my OAuth2 provider may issue a "super" type/scope token which grants access to both public and private pieces of my API, whereas for the third-party Client B, my provider may issue a "restricted" type/scope token which only grants access to the the public API calls. It should not be possible for app Client B to obtain app Client A's access token, which the current AccountManager/AccountManagerService implementation seems to allow. For, even if the user grants authorization to Client B for Client A's super token, the fact remains that my OAuth2 provider only intended to grant that token to Client A.
Am I overlooking something here? Is my belief that auth tokens to should be issued on a per-app/UID basis (each app being a distinct client) rational/practical, or are auth-tokens-per-device (each device being a client) the standard/accepted practice?
Or is there some flaw in my understanding of the code/security restrictions around AccountManager/AccountManagerService, such that this vulnerability does not actually exist? I've tested the above Client A/Client B scenario with the AccountManager and my custom authenticator, and my test client app B, which has a different package scope and UID, was able to obtain the auth token that my server had issued for my test client app A by passing-in the same authTokenType (during which I was prompted with "Access Request" grant screen, which I approved since I'm a user and therefore clueless)...
Possible Solutions
a. "Secret" authTokenType
In order to obtain the auth token, the authTokenType must be known; should the authTokenType be treated as a type of client secret, such that a token issued for a given secret token type may be obtained by only those "authorized" client apps which know the secret token type? This does not seem very secure; on a rooted device, it would be possible to examine the auth_token_type column of authtokens table in the system's accounts database and examine authTokenType values that are stored with my tokens. Thus, the "secret" auth token types used across all installations of my app (and any authorized third-party apps used on the device) will have been exposed in one central location. At least with OAuth2 client IDs/secrets, even if they must be packaged with the app, they are spread out among different client apps, and some attempt may be made to obfuscate them (which is better than nothing) to help discourage those who would unpackage/decompile the app.
b. Custom Auth Tokens
According to the docs for AccountManager.KEY_CALLER_UID and AuthenticatorDescription.customTokens, and the AccountManagerService source code I referenced earlier, I should be able to specify that my custom account type uses "custom tokens" and spin my own token caching/storage implementation within my custom authenticator, wherein I can obtain the UID of the calling app in order store/fetch auth tokens on a per-UID basis. Basically, I would have an authtokens table like the default implementation, except there would be an added uid column so that tokens are uniquely indexed on U̲I̲D̲, a̲c̲c̲o̲u̲n̲t̲, and A̲u̲t̲h̲ ̲T̲o̲k̲e̲n̲ ̲T̲y̲p̲e̲ (as opposed to just a̲c̲c̲o̲u̲n̲t̲ and A̲u̲t̲h̲ ̲T̲o̲k̲e̲n̲ ̲T̲y̲p̲e̲). This seems like a more secure solution than using "secret" authTokenTypes, since that would involve using the same authTokenTypes across all installations of my app/authenticator, whereas UIDs vary from system-to-system, and cannot be easily spoofed. Aside from the joyful overhead of getting to write and manage my own token caching mechanism, what downsides are there to this approach in terms of security? Is it overkill? Am I really protecting anything, or am I missing something such that even with such an implementation in place, it would still be easy enough for one malicious app client to obtain another app client's auth token using the AccountManager and authTokenType(s) which are not guaranteed to be secret (assuming that said malicious app does not know the OAuth2 client secret, and therefore cannot directly get a fresh token but could only hope to get one that was already cached in the AccountManager on behalf of the authorized app client)?
c. Send client ID/secret w/ OAuth2 token
I could stick with the AccountManagerService's default token storage implementation and accept the possibility of unauthorized access to my app's auth token, but I could force API requests to always include the OAuth2 client ID and client secret, in addition to the access token, and verify server-side that the app is the authorized client for which the token was issued in the first place. However, I would like to avoid this because A) AFAIK, the OAuth2 spec does not require client authentication for protected resource requests - only the access token is required, and B) I would like to avoid the additional overhead of authenticating the client on each request.
This isn't possible in the general case (all the server gets is a series of messages in a protocol - the code that generated those messages can't be determined). --Michael
But the same could be said of the initial client authentication in the OAuth2 flow during which the client is first issued the access token. The only difference is that instead of authenticating on just the token request, requests for protected resources would also be authenticated in the same way. (Note that the client app would be able to pass in its c̲l̲i̲e̲n̲t̲ ̲i̲d̲ and c̲l̲i̲e̲n̲t̲ ̲s̲e̲c̲r̲e̲t̲ through the loginOptions parameter of AccountManager.getAuthToken(), which my custom authenticator would just pass to my resource provider, per the OAuth2 protocol).
Key Questions
Is it indeed possible for one app to obtain another app's authToken for an account by invoking AccountManager.getAuthToken() with the same authTokenType?
If this is possible, is this a valid/practical security concern within an OAuth2 context?
You could never rely on an auth token given to a user remaining secret from that user...so it's reasonable for Android to ignore this security by obscurity goal in its design --Michael
BUT - I'm not concerned about the user (the resource owner) getting the auth token without my consent; I'm concerned about unauthorized clients (apps). If the user wants to be an attacker of his own protected resources, then he can knock himself out. I'm saying it should not be possible that a user installs my client app and, unwittingly, an "imposter" client app that is able to gain access to my app's auth token simply because it passed-in the correct authTokenType and the user was too lazy/unaware/rushed to examine the access request screen. This analogy may be a bit oversimplified, but I don't consider it "security by obscurity" that my installed Facebook app cannot read emails cached by my Gmail app, which is different from me (the user) rooting my phone and examining the cache contents myself.
The user needed to accept an (Android system provided) access request for the app to use your token... Given that, the Android solution seems OK - apps can't silently use a user's authentication without asking --Michael
BUT - This is also a problem of authorization - the auth token issued for my "official" client is the key to a set of protected resources for which that client and only that client is authorized. I suppose one could argue that since the user is the owner of those protected resources, if he accepts the access request from a third party client (be it a "sactioned" partner app or some phisher), then he is effectively authorizing the third-party client that made the request to access those resources. But I have issues with this:
The average user is not security-conscious enough to be able to competently make this decision. I don't believe we should depend solely on the user's judgment to tap "Deny" on Android's access request screen to prevent even a crude phishing attempt. When the user is presented with the access request, my authenticator could be super-detailed and enumerate all the types of sensitive protected resources (that only my client should be able to access) for which the user will be granting should he accept the request, and in most cases, the user will still be too unaware and is going to accept. And in other, more sophisticated phishing attempts, the "imposter" app is just going to look too "official" for the user to even raise an eyebrow at the access request screen. Or, here's a more blunt example - on the access request screen, my authenticator could simply say, "Do not accept this request! If you are seeing this screen, a malicious app is trying to gain access to your account!" Hopefully, in such a case, most users would deny the request. But - why should it even get that far? If Android simply kept auth tokens isolated to the scope of each app/UID for which they were issued, then this would be a non-issue. Let's simplify - even in the case where I have just one "official" client app, and therefore my resource provider does not even worry about issuing tokens to other, third-party clients, as a developer I should have the option of saying to the AccountManager, "No! Lock-down this auth token so that only my app has access." I can do this if I go along the "custom tokens" route, but even in that case, I would not be able to prevent the user from first being presented with the access request screen. At the very least, it should be better-documented that the default implementation of AccountManager.getAuthToken() will return the same auth token for all requesting apps/UIDs.
Even the Android docs recognize OAuth2 as the "industry standard" for authentication (and presumably authorization). The OAuth2 spec clearly states that access tokens are not to be shared between clients or divulged in any way. Why, then, does the default AccountManager implemenation/configuration make it so easy for a client to obtain the same cached auth token that was originally obtained from the service by another client? A simple fix within the AccountManager would be to only re-use cached tokens for the same app/UID under which the they were originally obtained from the service. If there is no locally cached auth token available for a given UID, then it should be obtained from the service. Or at least make this a configurable option for the developer.
In the OAuth 3-legged flow (which involves the user granting access to the client), isn't it supposed to be the service/resource provider (and not, say, the OS) which gets to A) authenticate the client and B) if the client is valid, present the user with the grant access request? Seems like Android is (incorrectly) usurping this role in the flow.
But the user can explicitly allow apps to re-use a previous authentication to a service, which is convenient for the user.--Michael
BUT - I don't think the ROI in convenience warrants the security risk. In cases where the user's password is being stored in the user's account, then really, the only convenience that is being bought for the user is that instead of sending a web request to my service to get a new, distinct token that is actually authorized for the requesting client, a locally cached token that is not authorized for the client is returned. So the user gains the slight convenience of seeing a "Signing In..." progress dialog for a couple of seconds fewer, at the risk of the user being majorly inconvenienced by having his resources stolen/misused.
Keeping in mind that I am committed to A) using the OAuth2 protocol for securing my API requests, B) providing my own OAuth2 resource/authentication provider (as opposed to authenticating with say, Google or Facebook), and C) utilizing Android's AccountManager to manage my custom account type and its token(s), are any of my proposed solutions valid? Which makes the most sense? Am I overlooking any of the pros/cons? Are there worthwhile alternatives that I have not thought of?
[Use] Alternative clients Don't have a secret API that attempts to only be accessible to an official client; people will get around this. Ensure all your public facing APIs are secure no matter what (future) client the user is using --Michael
BUT - Doesn't this defeat one of the key purposes of using OAuth2 in the first place? What good is authorization if all potential authorizees would be authorized to the same scope of protected resources?
Has anyone else felt this was an issue, and how did your work around it? I've done some extensive Googling to try to find if others have felt this to be a security issue/concern, but it seems that most posts/questions involving Android's AccountManager and auth tokens are about how to authenticate with a Google account, and not with a custom account type and OAuth2 provider. Moreover, I could not find anyone that was concerend about the possibility of the same auth token being used by different apps, which makes me wonder whether this is indeed a possibility/worthy of concern in the first place (see my first 2 "Key Questions" listed above).
I appreciate your input/guidance!
In Response to...
Michael's Answer - I think the major difficulties I have with your answer are:
I am still inclined to think of apps as being separate, distinct clients of a service, as opposed to the user/phone/device itself being one "big" client, and therefore a token that has been authorized for one app should not, by default, be transferable to one that has not. It seems like you may be hinting that it is moot to consider each app as a distinct client because of the possibility that,
the user could be running a rooted phone, and read off the token, gaining access to your private API... [or] if the user's system was compromised (the attacker could read off the token in this case)
and that therefore, in the grand scheme of things, we should consider the device to be a client of the service since we cannot guarantee security between apps on the device itself. It's true if the system itself has been compromised, then there can be no guarantee of authenticating/authorizing requests being sent from that device to a service. But the same could be said, of say, TLS; transport security is irrelevant if the endpoints themselves cannot be secured. And for the vast majority of Android devices, which are not compromised, I believe it is more secure to consider each app client as a distinct endpoint, instead of lumping them all into one by sharing the same auth token.
When presented with the "access request" screen (akin to the software user license agreement that we always read thoroughly before consenting and installing), I don't trust the user's judgment to distinguish a malicious/unauthorized client app from one that is not.
Is this a valid/practical security concern?
For the official Client A, my OAuth2 provider may issue a "super" type/scope token which grants access to both public and private pieces of my API
In the general case, you could never rely on an auth token given to a user remaining secret from that user. For example - the user could be running a rooted phone, and read off the token, gaining access to your private API. Ditto if the user's system was compromised (the attacker could read off the token in this case).
Put another way, there's no such thing as a "private" API that is at the same time accessible to any authenticated user, so it's reasonable for Android to ignore this security by obscurity goal in its design.
a malicious app ... could obtain access to my app's stored OAuth2 token
For the malicious app case, it begins to sound more reasonable that a malicious app shouldn't be able to use the client's token, as we expect Android's permission system to provide isolation of malicious apps (provided the user read / cared about the permissions they accepted when they installed it). However, as you say the user needed to accept an (Android system provided) access request for the app to use your token.
Given that, the Android solution seems OK - apps can't silently use a user's authentication without asking, but the user can explicitly allow apps to re-use a previous authentication to a service, which is convenient for the user.
Possible Solutions Review
"Secret" authTokenType ... does not seem very secure
Agreed - it's just another layer of security through obscurity; it sounds like any app wishing to share your authentication would have had to look up what the authTokenType was anyway, so adopting this approach just makes it a bit more awkward for this hypothetical app developer.
Send client ID/secret w/ OAuth2 token ... [to] verify server-side that the app is the authorized client
This isn't possible in the general case (all the server gets is a series of messages in a protocol - the code that generated those messages can't be determined). In this specific instance, it might protect against the more limited threat of a (non-root) alternative client / malicious app - I'm not familiar enough with the AccountManager to comment (ditto for your custom auth tokens solutions).
Suggestion
You described two threats - malicious apps that a user doesn't want to have access to their account, and alternative clients that you (the developer) doesn't want using parts of the API.
Malicious apps: Consider how sensitive the service you are providing is, and if it's not more sensitive than e.g. Google / twitter accounts, just rely on Android's protections (permissions on install, Access Request screen). If it is more sensitive, consider whether your constraint of utilizing Android's AccountManager is appropriate. To strongly protect the user against malicious use of their account, try two factor authentication for dangerous actions (c.f. adding a new recipient's account details in online banking).
Alternative clients: don't have a secret API that attempts to only be accessible to an official client; people will get around this. Ensure all your public facing APIs are secure no matter what (future) client the user is using.
Your observation is correct. Authenticator will run with same UID as the installing app. When another app connects to Account manager and get token for this authenticator, it will bind to your provided authenticator service. It will run as your UID, so new accounts will be related to this Authenticator. When app calls for getAuthToken, binding will happen and Authenticator will still run in same UId. Default built in permissions check for account's UID, so that different Authenticator could not access another account from different Authenticator.
You can solve this issue with using "Calling UID" for addAccount and GetAuthToken since account manager service adds that to bundle. Your authenticator implementation can check that.
#Override
public Bundle getAuthToken(AccountAuthenticatorResponse response, Account account,
String authTokenType, Bundle loginOptions) throws NetworkErrorException {
Log.v(
TAG,
"getAuthToken() for accountType:" + authTokenType + " package:"
+ mContext.getPackageName() + "running pid:" + Binder.getCallingPid()
+ " running uid:" + Binder.getCallingUid() + " caller uid:"
+ loginOptions.getInt(AccountManager.KEY_CALLER_UID));
...
}
I suggest to follow authorization flow instead of storing client secret in your native app, because other developers can extract that secret. Your app is not a web app and should not have secrets.
When you are adding an account, you can query the callingUId as well. You need to setUserData at your addAccount related activity which will be running as your app's UID, so it can call setUserData.
getUserData and setUserData uses built in sqllite database, so you don't need to build cache by yourself. You can only store string type, but you can parse json and store extra info per account.
When different third party app queries account and calls for getAuthtoken with your account, you can check UID in the account' userdata. If calling UID is not listed, you can do the prompt and/or other things to get permission. If it is permitted, you can add new UID to the account.
Sharing tokens between apps:
Each app is normally registered with different clientid and they should not share token. Token is for a client app.
Storage:
AccountManager is not encrypting your data. If you need more secure solution, you should encrypt the tokens and then store it.
I'm facing the same architectural problem for an app.
The solution that I got is to associate/hash the oauth token, with the app vendor token (ex. the token that facebook give to an app), and to device id (android_id). So only the app authorized, for the device is able to use the token from account manager.
Of course, it's just a new layer of security, but no bullet proof.
I reckon #Michael answered the question perfectly; however, to make the answer more sensible and short to those looking for a quick answer I am writing this.
Your concern about the security of android AccountManager is correct, but this is what OAuth is meant to be, upon which android AccountManager relies.
In other words, if you are looking for a very secure authentication mechanism this would not be a good option for you. You should not rely on any cached tokens for authentication, since they can be easily revealed to the intruder in case there is any security vulnerability on the user's device such as inadvertently granting access permission to the intruder, running a rooted device, etc.
The better alternative to OAuth in more secure authentication systems, e.g. online banking apps, is using asymmetric encryption using public and private keys, in which the user is required to enter their password every time for using the services. The password is then encrypted using the public key on the device and sent to the server. Here, even if the intruder gets known of the encrypted password, he cannot do anything with that because he cannot decrypt it with that public key and needs only the private key of the server.
Anyway, if one wants to make use of the AccountManager system of the android as well as maintain high level of security, it would be possible by not saving any tokens on the device. The getAuthToken method from AbstractAccountAuthenticator can then be overriden like this:
#Override
public Bundle getAuthToken(AccountAuthenticatorResponse response, Account account, String
authTokenType, Bundle options) throws NetworkErrorException {
AuthenticatorManager authenticatorManager = AuthenticatorManager.authenticatorManager;
Bundle result;
AccountManager accountManager = AccountManager.get(context);
// case 1: access token is available
result = authenticatorManager.getAccessTokenFromCache(account, authTokenType,
accountManager);
if (result != null) {
return result;
}
final String refreshToken = accountManager.getPassword(account);
// case 2: access token is not available but refresh token is
if (refreshToken != null) {
result = authenticatorManager.makeResultBundle(account, refreshToken, null);
return result;
}
// case 3: neither tokens is available but the account exists
if (isAccountAvailable(account, accountManager)) {
result = authenticatorManager.makeResultBundle(account, null, null);
return result;
}
// case 4: account does not exist
return new Bundle();
}
In this method, neither case 1, case 2 nor case 4 holds true because there is no saved token, even though the account is there. Therefore, only case 3 will be returned which can then be set in the relevant callback to open an Activity in which the user enters username and password for authentication.
I am not sure of being on the right track in further describing this here, but my website posts on AccountManager may help just in case.
This question is about trying to understand the security risks involved in implementing oauth on a mobile platform like Android. Assumption here is that we have an Android application that has the consumer key/secret embedded in the code.
Assuming a consumer secret has been compromised, and a hacker has gotten a hold of it, what are the consequences of this ?
Compromised Consumer Secret assumptions
Am I correct in stating that a compromised consumer secret as such has no effect on the user's security, or any data stored at the OAuth enabled provider that the user was interacting with. The data itself is not compromised and cannot be retrieved by the hacker.
The hacker would need to get a hold of a valid user access token, and that's a lot harder to get.
What could a hacker do with a compromised consumer secret ?
Am I also correct in stating the following :
The hacker can setup/publish an
application that imitates my app.
The hacker can attract users that will go
through the OAuth flow, retrieving an
access token via the hackers OAuth
dance (using the compromised consumer
key/secret).
The user might think
he's dealing with my app, as he will
see a familiar name (consumer key)
during the authorization process.
When a consumer issues a request via
the hacker, the hacker can easily
intercept the access token, and
combined with the consumer secret can
now sign requests on my behalf to
gain access to my resources.
End-user impact
In the assumption that
a hacker has setup an application /
site using my consumer secret
one of my users was tricked into authorizing
access to that application / site
The following might happen :
the end-user may being noticing that something fishy is going on, and inform the service provider (ex: Google) about the malicious app
the service provider can then revoke the consumer key/secret
OAuth consumer (my application) impact :
My app (containing the consumer secret) would need to be updated, as otherwise all my clients would not be able to authorize my application do to requests on their behalf anymore (as my consumer secret would no longer be valid).
Delegating all OAuth traffic
Although it would be possible to delegate a lot of the OAuth interactions via an intermediate webserver (doing the OAuth dance and sending the access token to the user), one would have to proxy all service interactions also, as the consumer key/secret is required for signing each request. Is this the only way to keep the consumer key/secret outside of the mobile app, and stored in a more secure place on the intermediate webserver ?
Alternatives
Are there alternatives for this proxy-ing ? Is it possible to store the consumer secret at the intermediate webserver, and have some kind of mechanism that the Android application (published in the market and properly signed), can do a secure request to the intermediate webserver to fetch the consumer secret and store it internally in the app ? Can a mechanism be implemented that the intermediate webserver "knows" that this is an official android app that is requesting to fetch the consumer secret, and that the intermediate webserver will only handout the consumer secret to that particular android app ?
Summary: I would just take the risk and keep the secret in the client app.
Proxy server alternative:
The only way you can reasonable mitigate the problems I list below and make the proxy-ing work, would be to go the whole nine yards - move all the business logic for dealing with the resources on the third party webservice to your proxy server, and make the client app dumb terminal with rich UI. This way, the only actions the malicious app would be able to make the proxy perform on its behalf would be only what your business logic legitimately needs.
But now you get in the realm of a whole slew of other problems having to deal with reliability and scalability.
Long deliberation on why simple proxy wouldn't work:
Some people, when confronted with a
problem, think “I know, I'll add my
own proxy server” Now they have two
problems. (with apologies to Jamie
Zawinski)
Your assumptions are largely right. Right down to the point where you start thinking about your own server, whether it keeps the secret and proxies the calls for the client app, or it attempts to determine if the app is legitimate and give it the secret. In both approaches, you still have to solve the problem of "is this request coming from a piece of code I wrote"?
Let me repeat - there is no way to distinguish on the wire that particular piece of software is running. If the data in the messages looks right, nothing can prove it's another app that's sending that message.
At the end of the day, if I am writing a malicious app, I don't care if I actually know the real secret, as long as I can make somebody that knows it do a work on my behalf. So, if you think a malicious app can impersonate your app to the third party OAuth servers, why are you certain it can't impersonate your app to your proxy?
But wait, there's more. The domain at which your proxy service is located, is your identity to both your clients and the OAuth provider (as shown to the end user by the OAuth provider). If a malicious app can make your server do bad stuff, not only is your key revoked, but your public web identity is also not trusted anymore.
I will start with the obvious - there is no way to distinguish on the wire that particular piece of software is running. If the data in the messages looks right, nothing can prove it's another app that's sending that message.
Thus, any algorithm that relies on app-side stored secret can be spoofed. OAuth's strength is that it never gives the user's credentials to the app, instead giving the app temporary credentials of it's own that the user can revoke if necessary.
Of course, the weak point here is that a sufficiently good app can get the user to trust it and not revoke the credentials, before it finished its nefarious deeds.
However, one way to mitigate this is Google's approach of using 3-legged OAuth, instead of the standard 2-legged. In the 3-legged OAuth, there's no pre-assigned secret, but on every authentication a new access token secret is issued, along with each access token. While ultimately this suffers from the same drawback, as a bad app can read the good app's token secret from its process, it does result in the user having to approve the app access every time it needs new access token.
And of course, this also means that it's a bit more inconvenient and annoying for the user.