Best way to generate API Key? - api

Use Case
I'm building an iPhone app with a simple signup and login.
When a user signs up/logs in, I want the Ruby (Sinatra) server to generate/fetch and return an access token for that user that the iPhone client can then send with every subsequent request using Basic Authentication over HTTPS.
I'm not yet implementing OAuth 2.0 so that third party apps can access the server. Right now, I'm just building a simple, internal API (for my own, first-party, iPhone app).
Example
Basically, I want to generate a secret API key like Stripe's: https://manage.stripe.com/account/apikeys
For example: sk_test_NMss5Xyp42TnLD9tW9vANWMr
What's the best way to do that, say in Ruby?

The Ruby stdlib provides an entire class of secure random data generators called SecureRandom. Whatever you want, you can probably find it there.
Stripe's keys are essentially URL-safe Base64. You can get something very similar like so:
require 'securerandom'
p "sk_test_" + SecureRandom.urlsafe_base64
(Stripe does strip out non-alphanumeric characters, but that's trivial to do with gsub if you don't want hyphens in your keys.)

I recently published a gem called sssecrets (for Simple Structured Secrets) to solve this problem.
Sssecrets is a reusable implementation of GitHub's API token format (which is also used by NPM), and it's designed to make it simple for developers to issue secure secret tokens that are easy to detect when leaked.
Simple Structured Secrets provides a compact format with properties that are optimized for detection with static analysis tools. That makes it possible to automatically detect when secrets are leaked in a codebase using features like GitHub Secret Scanning or GitLab Secret Detection.
Why Use Structured Secrets?
Using a structured format for secrets is really important for security reasons. If you're a developer and your application issues some kind of access tokens (API keys, PATs, etc), you should try to format these in a way that both identifies the string as a secret token and provides insight into its permissions. For bonus points, you should also provide example (dummy) tokens and regexes for them in your documentation.
Here's an example of a bad secret. As of the time of writing, HashiCorp Vault's API access tokens look like this (ref):
f3b09679-3001-009d-2b80-9c306ab81aa6
You might think that this is pretty is a pretty easy pattern to search for, but here's the issue: It's just a UUID string.
While random, strings in this format are used in many places for non-sensitive purposes. Meaning that, given a random UUID formatted string, it's impossible to know whether it's a sensitive API credential or a garden-variety identifier for something mundane. In cases like these, secret scanning can't help much.
What's in a Structured Secret?
Structured secrets have three parts:
A prefix (2-10 characters, defined by you)
30 characters of randomness
A 6 character checksum
That's it!
Here's the format:
[prefix]_[randomness][checksum]
An example Sssecret, with an org of t and a type of k, looks like this:
tk_GNrRoBa1p9nuwm7XrWkrhYUNQ7edOw4GUp8I
Prefix
Token prefixes are a simple and effective method to make tokens identifiable. Slack, Stripe, GitHub, and others have adopted this approach to great effect.
Sssecrets allows you to provide two abbreviated strings, org and type, which together make up the token prefix. Generally, org would be used to specify an overarching identifier (like your company or app), while type is intended to identify the token type (i.e., OAuth tokens, refresh tokens, etc) in some way. To maintain a compact and consistent format for Sssecret tokens, org and type together should not exceed 10 characters in length.
Entropy
Simple Structured Secret tokens have an entropy of 178:
Math.log(((“a”..“z”).to_a + (“A”..“Z”).to_a + (0..9).to_a).length)/Math.log(2) * 30 = 178
See the GitHub blog.
Checksum
The random component of the token is used to calculate a CRC32 checksum. This checksum is encoded in Base62 and padded with leading zeroes to ensure it's always 6 characters in length.
The token checksum can be used as a first-pass validity check. Using these checksums, false positives can be more or less eliminated when a codebase is being scanned for secrets, as fake tokens can be ignored without the need to query a backend or database.
Note that this library can only check whether a given token is in the correct form and has a valid checksum. To fully determine whether a given token is active, you'll still need to implement your own logic for checking the validity of tokens you've issued.
Another note: Because Sssecrets uses the same format as GitHub tokens, you can also perform offline validation of GitHub-issued secrets with SimpleStructuredSecrets#validate.
Further Reading
You can learn more about GitHub's design process and the properties of this API token format on the GitHub blog.

Related

securing credentials on front end react-native

I am creating an app using react-native. This app requires some sensitive data which must be stored securely and there are various options for that e.g, expo-secure-store.
Now i am a but confused regarding securing the data on front end.
I am using react-native-async-storage to store other data on front end.
Now it is treated as a bad practice to use the same for sensitive data.
But my question is, say i use expo-secure-store for sensitive data, but at the time of saving it like this;
SecureStore.setItemAsync(key, value);
where value is the sensitive part, isn't that still getting exposed while setting it in the code.
Please explain this and describe some better practices to store (or access) sensitive data on front end.
Thanks!
The documentation for the Google Maps Android SDK has instructions for restricting the API key usage to an app fingerprint: https://developers.google.com/maps/documentation/android-sdk/get-api-key
This reduces the risk of including the key in your app by only allowing the key to be used from a source that matches the fingerprint of the app certificate.
In practice the value of a Google Maps API key is fairly low, and is not the most attractive target for a bad actor. Frontend API keys are sensitive in that you can be billed for their usage, but unless you are specifically targeted, it's not a likely attack vector.
Truly sensitive keys, like those used to generate auth credentials or payment data, should always be kept on the backend, and any decent third-party service will be set up in a way that forces this to be the case (for example, Stripe).
You may get better answers by asking how or when to store specific keys.

Architecturing testmode/livemode using OAuth 2 token

The title is a bit obscure. I'm interested about some feedbacks on a specific architecture pattern.
Let's take as an example the Stripe API: when you are using this API, the system is basically broken into two parts: live mode and test mode. If you hit the "/customers" end-point, you can either retrieve test mode customers or live mode customers, based on the type of API key used.
I'm asking myself how I could implement such a pattern using an OAuth 2 access token.
In my workflow, I have a single application page (JavaScript) that communicates through my API. I have a "live"/"test" switch, so basically my whole website is replicated into two distinct environments.
When I log in into my application, my authorization server creates a unique access token (OAuth 2 Bearer token), that is send for each requests. But obviously, my access token is tied to the "session", not an "environment" (live or false), so if I want to implement a switch live mode / test mode, I cannot rely on the token, because the token is "generic".
I've thought about two options:
Depending on live mode or test mode, I send an additional header to all my request (like X-Livemode which is either true or false). Then, in my back-end, I reuse this header to automatically adds a filter on all my requests.
If I switch to live mode or test mode, I ask my authorization server another access token. This would means that access token would have additional context information. However this seems a bit complicated, and I'm not sure that OAuth 2 spec allows token to have such additional information.
I'm not sure if this post is clear or not :p.
The second part of the question, is what is the best way to implement such a system where all the resources are basically duplicated between live / test mode ?
In my understand, it should be as simple as adding a "isLivemode" property to all resources, and make sure that all my SQL queries are aware of this. Is this correct?
Thanks!
A much simpler solution I've used in the past (albeit a bit of a workaround) is just to append "live" or "test" (base64 or hex encoded) to the api key, like so:
Imagine your actual key is:
9a0554259914a86fb9e7eb014e4e5d52
In your key presentation, present your key to the user as:
9a0554259914a86fb9e7eb014e4e5d526c697665
Then use a regular expression to strip off the known characters.
Alternatively, if you're equipped to handle key-value maps, a more "OAuth2-spec" approach would be to generate unique keys for live and test and do a key-value map lookup on the request to determine if one belongs to live or test.

Do I need a cryptographically secure random number?

I'm writing a webservice in Go.
Upon login, the user is returned a token, which behaves roughly like a cookie in the sense that the user must pass it in each subsequent request in order to be recognized.
Does my token generator has to be "cryptographically secure", ie. generated with high entropy?
How can I achieve this in Go, preferably using standard libraries or libraries written by crypto-competent people unlike me?
It would be beneficial for the token generator to be cryptographically secure, to reduce the ability of attackers to guess new session tokens and acquire the privileges along with them. crypto/rand implements such a random number generator, including functions that allow you to generate random integers, prime numbers and bytes suitable for this.
Yes, use a crytographic hash. You can use something like gorilla/securecookie to generate a key and provide cookie storage: http://www.gorillatoolkit.org/pkg/securecookie
Note that if you are relying upon the cookie alone for verification that you open yourself up to replay attacks. Use the cookie to trigger a server-side check (user ID == active/valid) or bounce then out if the ID doesn't exist.

Clarification on HMAC authentication with WCF

I have been following a couple of articles regarding RESTful web services with WCF and more specifically, how to go about authentication in these. The main article I have been referencing is Aaron Skonnard's RESTful Web Services with WCF 3.5. Another one that specifically deals with HMAC authentication is Itai Goldstiens article which is based on Skonnards article.
I am confused about the "User Key" that is referenced to in both articles. I have a client application that is going to require a user to have both a user name and password.
Does this then mean that the key I use to initialise the
System.Security.Cryptography.HMACMD5 class is simply the users
password?
Given the method used to create the Mac in Itai's article
(shown below), am I right is thinking that key is the users
password and text is the string we are using confirm that the
details are in fact correct?
public static string EncodeText(byte[] key, string text, Encoding encoding)
{
HMACMD5 hmacMD5 = new HMACMD5(key);
byte[] textBytes = encoding.GetBytes(text);
byte[] encodedTextBytes =
hmacMD5.ComputeHash(textBytes);
string encodedText =
Convert.ToBase64String(encodedTextBytes);
return encodedText;
}
In my example, the text parameter would be a combination of request uri, a shared secret and timestamp (which will be available as a request header and used to prevent replay attacks).
Is this form of authentication decent? I've come across another thread here that suggests that the method defined in the articles above is "..a (sic) ugly hack." The author doesn't suggest why, but it is discouraging given that I've spent a few hours reading about this and getting it working. However, it's worth noting that the accepted answer on this question talks about a custom HMAC authorisation scheme so it is possible the ugly hack reference is simply the implementation of it rather than the use of HMAC algorithms themselves.
The diagram below if from the wikipedia article on Message Authentication Code. I feel like this should be a secure way to go, but I just want to make sure I understand it's use correctly and also make sure this isn't simply some dated mechanism that has been surpassed by something much better.
The key can be the user's password, but you absolutely should not do this.
First - the key has an optimal length equal to the size of the output hash, and a user's password will rarely be equal to that.
Second, there will never be enough randomness (entropy to use the technical term) in those bytes to be an adequate key.
Third, although you're preventing replay attacks, you're allowing anyone potentially to sign any kind of request, assuming they can also get hold of the shared secret (is that broadcast by the server at some point or is it derived only on the client and server? If broadcast, a man-in-the-middle attack can easily grab and store that - height of paranoia, yes, but I think you should think about it) unless the user changes their password.
Fourth - stop using HMACMD5 - use HMAC-SHA-256 as a minimum.
This key should at the very least be a series of bytes that are generated from the user's password - typically using something like PBKDF2 - however you should also include something transitory that is session-based and which, ideally, can't be known by an attacker.
That said, a lot of people might tell you that I'm being far too paranoid.
Personally I know I'm not an expert in authentication - it's a very delicate balancing act - so I rely on peer-reviewed and proven technologies. SSL (in this case authentication via client certificates), for example, might have it's weaknesses, but most people use it and if one of my systems gets exploited because of an SSL weakness, it's not going to be my fault. However if an exploit occurs because of some weakness that I wasn't clever enough to identify? I'd kick myself out of the front door.
Indidentally, for my rest services I now use SCRAM for authentication, using SHA512 and 512 bits of random salt for the stretching operation (many people will say that's excessive, but I won't have to change it for a while!), and then use a secure token (signed with an HMAC and encrypted with AES) derived from the authentication and other server-only-known information to persist an authenticated session. The token is stateless in the same way that Asp.Net forms authentication cookies are.
The password exchange works very well indeed, is secure even without SSL (in protecting the password) and has the added advantage of authenticating both client and server. The session persistence can be tuned based on the site and client - the token carries its own expiry and absolute expiry values within it, and these can be tuned easily. By encrypting client ID information into that token as well, it's possible to prevent duplication on to another machine by simply comparing the decrypted values from the client-supplied values. Only thing about that is watching out for IP address information, yes it can be spoofed but, primarily, you have to consider legitimate users on roaming networks.

Creating an API for mobile applications - Authentication and Authorization

Overview
I'm looking to create a (REST) API for my application. The initial/primary purpose will be for consumption by mobile apps (iPhone, Android, Symbian, etc). I've been looking into different mechanisms for authentication and authorization for web-based APIs (by studying other implementations). I've got my head wrapped around most of the fundamental concepts but am still looking for guidance in a few areas. The last thing I want to do is reinvent the wheel, but I'm not finding any standard solutions that fits my criteria (however my criteria my be misguided so feel free to critique that as well). Additionally, I want the API to be the same for all platforms/applications consuming it.
oAuth
I'll go ahead and throw out my objection to oAuth since I know that will likely be the first solution offered. For mobile applications (or more specifically non-web applications), it just seems wrong to leave the application (to go to a web-browser) for the authentication. Additionally, there is no way (I am aware of) for the browser to return the callback to the application (especially cross-platform). I know a couple of apps that do that, but it just feels wrong and gives a break in the application UX.
Requirements
User enters username/password into application.
Every API call is identified by the calling application.
Overhead is kept to a minimum and the auth aspect is intuitive for developers.
The mechanism is secure for both the end user (their login credentials are not exposed) as well as the developer (their application credentials are not exposed).
If possible, not require https (by no means a hard requirement).
My Current Thoughts on Implementation
An external developer will request an API account. They will receive an apikey and apisecret. Every request will require at minimum three parameters.
apikey - given to developer at regisration
timestamp - doubles as a unique identifier for each message for a given apikey
hash - a hash of the timestamp + the apisecret
The apikey is required to identify the application issuing the request. The timestamp acts similarly to the oauth_nonce and avoids/mitigates replay attacks. The hash ensures that request was actually issued from the owner of the given apikey.
For authenticated requests (ones done on the behalf of a user), I'm still undecided between going with an access_token route or a username and password hash combo. Either way, at some point a username/password combo will be required. So when it does, a hash of several pieces of information (apikey, apisecret, timestamp) + the password would be used. I'd love feedback on this aspect. FYI, they would have to hash the password first, since I don't store the passwords in my system without hashing.
Conclusion
FYI, this isn't a request for how to build/structure the API in general only how to handle the authentication and authorization from solely within an application.
Random Thoughts/Bonus Questions
For APIs that only require an apikey as part of the request, how do you prevent someone other than the apikey owner from being able to see the apikey (since sent in the clear) and make excessive requests to push them over usage limits? Maybe I'm just over thinking this, but shouldn't there be something to authenticate that a request was verified to the apikey owner? In my case, that was the purpose of the apisecret, it is never shown/transmitted without being hashed.
Speaking of hashes, what about md5 vs hmac-sha1? Does it really matter when all of the values are hashed with with sufficiently long data (ie. apisecret)?
I had been previously considering adding a per user/row salt to my users password hash. If I were to do that, how could the application be able to create a matching hash without knowing the salt used?
The way I'm thinking about doing the login part of this in my projects is:
before login the user requests a login_token from the server. These are generated and stored on the server on request, and probably have a limited lifetime.
to login the application calculates the hash of the users password, then hashes the password with the login_token to get a value, they then return both the login_token and the combined hash.
The server checks the login_token is one that it has generated, removing it from its list of valid login_tokens. The server then combines its stored hash of the user's password with the login_token and ensures that it matches the submitted combined token. If it matches you have authenticated your user.
Advantages of this are that you never store the user's password on the server, the password is never passed in the clear, the password hash is only passed in the clear on account creation (though there may be ways around this), and it should be safe from replay attacks as the login_token is removed from the DB on use.
That's a whole lot of questions in one, I guess quite a few people didn't manage to read all the way to the end :)
My experience of web service authentication is that people usually overengineer it, and the problems are only the same as you would encounter on a web page. Possible very simple options would include https for the login step, return a token, require it to be included with future requests. You could also use http basic authentication, and just pass stuff in the header. For added security, rotate/expire the tokens frequently, check the requests are coming from the same IP block (this could get messy though as mobile users move between cells), combine with API key or similar. Alternatively, do the "request key" step of oauth (someone suggested this in a previous answer already and it's a good idea) before authenticating the user, and use that as a required key to generate the access token.
An alternative which I haven't used yet but I've heard a lot about as a device-friendly alternative to oAuth is xAuth. Have a look at it and if you use it then I'd be really interested to hear what your impressions are.
For hashing, sha1 is a bit better but don't get hung up about it - whatever the devices can easily (and quickly in a performance sense) implement is probably fine.
Hope that helps, good luck :)
So what you're after is some kind of server side authentication mechanism that will handle the authentication and authorisation aspects of a mobile application?
Assuming this is the case, then I would approach it as follows (but only 'cos I'm a Java developer so a C# guy would do it differently):
The RESTful authentication and authorisation service
This will work only over HTTPS to prevent eavesdropping.
It will be based on a combination of RESTEasy, Spring Security and CAS (for single sign on across multiple applications).
It will work with both browsers and web-enabled client applications
There will be a web-based account management interface to allow users to edit their details, and admins (for particular applications) to change authorisation levels
The client side security library/application
For each supported platform (e.g.
Symbian, Android, iOS etc) create a
suitable implementation of the
security library in the native
language of the platform (e.g. Java,
ObjectiveC, C etc)
The library
should manage the HTTPS request
formation using the available APIs
for the given platform (e.g. Java
uses URLConnection etc)
Consumers of the general authentication and
authorisation library ('cos that's
all it is) will code to a specific
interface and won't be happy if it
ever changes so make sure it's very
flexible. Follow existing design
choices such as Spring Security.
So now that the view from 30,000ft is complete how do you go about doing it? Well, it's not that hard to create an authentication and authorisation system based on the listed technologies on the server side with a browser client. In combination with HTTPS, the frameworks will provide a secure process based on a shared token (usually presented as a cookie) generated by the authentication process and used whenever the user wishes to do something. This token is presented by the client to the server whenever any request takes place.
In the case of the local mobile application, it seems that you're after a solution that does the following:
Client application has a defined Access Control List (ACL) controlling runtime access to method calls. For example, a given user can read a collection from a method, but their ACL only permits access to objects that have a Q in their name so some data in the collection is quiety pulled by the security interceptor. In Java this is straightforward, you just use the Spring Security annotations on the calling code and implement a suitable ACL response process. In other languages, you're on your own and will probably need to provide boilerplate security code that calls into your security library. If the language supports AOP (Aspect Oriented Programming) then use it to the fullest for this situation.
The security library caches the complete list of authorisations into it's private memory for the current application so that it doesn't have to remain connected. Depending on the length of the login session, this could be a one-off operation that never gets repeated.
Whatever you do, don't try to invent your own security protocol, or use security by obscurity. You'll never be able to write a better algorithm for this than those that are currently available and free. Also, people trust well known algorithms. So if you say that your security library provides authorisation and authentication for local mobile applications using a combination of SSL, HTTPS, SpringSecurity and AES encrypted tokens then you'll immediately have creditibility in the marketplace.
Hope this helps, and good luck with your venture. If you would like more info, let me know - I've written quite a few web applications based on Spring Security, ACLs and the like.
Twitter addressed the external application issue in oAuth by supporting a variant they call xAuth. Unfortunately there's already a plethora of other schemes with this name so it can be confusing to sort out.
The protocol is oAuth, except it skips the request token phase and simply immediately issues an access token pair upon receipt of a username and password. (Starting at step E here.) This initial request and response must be secured - it's sending the username and password in plaintext and receiving back the access token and secret token. Once the access token pair has been configured, whether the initial token exchange was via the oAuth model or the xAuth model is irrelevant to both the client and server for the rest of the session. This has the advantage that you can leverage existing oAuth infrastructure and have very nearly the same implementation for mobile/web/desktop applications. The main disadvantage is that the application is granted access to the client's user name and password, but it appears like your requirements mandate this approach.
In any case, I'd like to agree with your intuition and that of several other answerers here: don't try to build something new from scratch. Security protocols can be easy to start but are always hard to do well, and the more convoluted they become the less likely your third-party developers are to be able to implement against them. Your hypothetical protocol is very similar to o(x)Auth - api_key/api_secret, nonce, sha1 hashing - but instead of being able to use one of the many existing libraries your developers are going to need to roll their own.
Super late to the party but I wanted to throw in some additional points to consider for anyone interested in this issue. I work for a company doing mobile API security solutions (approov) so this whole area is definitely relevant to my interests.
To start with, the most important thing to consider when trying to secure a mobile API is how much it is worth to you. The right solution for a bank is different to the right solution for someone just doing things for fun.
In the proposed solution you mention that a minimum of three parameters will be required:
apikey - given to developer at registration
timestamp - doubles as a unique identifier for each message for a given apikey
hash - a hash of the timestamp + the apisecret
The implication of this is that for some API calls no username/password is required. This can be useful for applications where you don't want to force a login (browsing in online shops for example).
This is a slightly different problem to the one of user authentication and is more like authentication or attestation of the software. There is no user, but you still want to ensure that there is no malicious access to your API. So you use your API secret to sign the traffic and identify the code accessing the API as genuine. The potential problem with this solution is that you then have to give away the secret inside every version of the app. If someone can extract the secret they can use your API, impersonating your software but doing whatever they like.
To counter that threat there are a bunch of things you can do depending on how valuable the data is. Obfuscation is a simple way to make it harder to extract the secret. There are tools that will do that for you, more so for Android, but you still have to have code that generates your hash and a sufficiently skilled individual can always just call the function that does the hashing directly.
Another way to mitigate against excessive use of an API that doesn't require a login is to throttle the traffic and potentially identify and block suspect IP addresses. The amount of effort you want to go to will largely depend upon how valuble your data is.
Beyond that you can easily start getting into the domain of my day job. Anyway, it's another aspect of securing APIs that I think is important and wanted to flag up.