Rest API under https security - api

I am new and need directions so I can ask the correct questions. Here's the deal:
I have developed a REST API under HTTPS.
The user must provide a valid token to use the API.
The token expires after not being used for more than 5 minutes.
To obtain the token, the client must call the authentication API passing his private primary or secondary key, along with his user number.
Each key is unique, and on the database I save it's hash.
The user passes his primary or secondary key through the header with key "pk" or "sk" and "usernumber".
The server will get those keys and send to the database, which will apply the hash and check if they are valid.
Once the keys are valid, a token itself is generated on the database, and returned to the user.
My concern regards passing the primary key or secondary key on the headers. I am not sure if someone can obtain those data from outside and neither if it is the best practice. I am trying to get some directions, and I have came upon basic auth, oauth, and others. But they all seem to be on HTTP.
I have not found much about API HTTPS, so I also need some directions here. Can I make my API accept only https requests? If so, does the same security rules apply?
Thanks in advance.

There are 4 security aspects to consider. Most of the frameworks define the flow for Authentication and Authorization. Some frameworks define Integrity as well via Signatures.
But almost all heavily rely on encrypted data for for Confidentiality. i.e they recommend HTTPS if the communication is based on HTTP
Authentication:
Identifying who is talking to your API.
Authorisation:
Once you have identified who is talking to your API, ensuring they have the permission to talk to. If authentication is like checking someone's Id and allowing them into the building. Then authorisation is like allowing them to go into room for which they have access code.
Integrity:
One you know who are you talking to and what they are allowed to do, you still need to make sure that data you are receiving is from them and not tampered data.
Confidentiality
May be they are not tampering the data but reading all the data over the wire so later they can use that data and pretend to be the person you trust. So except for the sender and receiver no one else to see the data.
Note:
The above 4 aspects are for security on the flow.
You also have to consider security at rest. You seems to have strong design here on the server side for this aspect.
Have you considered what would you do when the token expires after 5 minutes. You user won't be happy entering user number and primary key/secondary key every 5 minutes. And if you plan to store it on client side so you can automate it every 5 minute, then you have to think about where would you store it in the client side and security at rest aspect for that

First of all: regarding HTTPS VS HTTP.
HTTPS is HTTP over TLS, where TLS is another layer of protection meant to secure the communication channel. All HTTP rules regarding headers apply to HTTPS too. TLS will protect your data confidentiality and integrity. It will protect the whole HTTP request including headers and body.
Regarding passing secrets as headers.
It's ok to pass secrets as headers or body. It's not ok, to pass secrets in URL. It's not ok to log out secrets on servers and proxies along the way. It's not ok to implement your own authentication mechanisms unless really needed.
If you want to read more about what is required to protect the communication channel (and the rest of the application), look into the OWASP Application Security Verification Standard.

Related

Is there a way to secure an API key on a frontend page?

My service allow any HTML documents to be converted to PDF using a POST request.
It is mostly used on the backend of my client's server and thus, the API key used for the communication is kept private.
Now, I'm thinking of a way to let my client's visitors be able to call my service on behalf of my client API key, without exposing this secure API Key.
My main issue here is security. If my client add an XHR POST requests that contains the API key, someone can take that API key and use it for their own purpose and abusing my client's account.
I could filter by domain, but this is easily spoofed so it's not possible.
I was wondering if there was a way to call a private service and be identified without risking its identity to be stolen, from the client ('s client) side?
If you're providing this sublet for authenticated users, then it's fairly trivial to give them unique keys (something that hashes their user ID or session against the API key and an initial timestamp, and checks it / logs it / looks for brutes before accessing the API). If you're doing it on the open web, without any kind of user authentication, then rate limiting gets very tricky indeed. Generally you'd want to use a combination of session hashes, IP address, operating system and browser data to create an anonymous profile that gets a temporary key on the frontend. One fairly solid way to do this is to force users through a CAPTCHA before serving a temporary key that allows them a limited number of uses of the permanent key. Any user whose ip/browser/session matches the existing attributes of a known client key is shunted to that one (and gets to skip the CAPTCHA); anyone who doesn't match an existing profile gets the CAPTCHA. That makes you a less attractive target for spoofing. On top of that, you should always rate-limit the entire thing, within a reasonable number of hits per day based on what kind of traffic you expect (or can afford), just so you don't have any surprises. This is the minimal security you'd want if your client's money is on the line every time their API key is used. It will require a simple database to store these "profiles", track usage, check for brutes and maintain the currently valid client keys. Client keys should always be expired regularly - either with a time diff against when they were created, or a regular cron process, or a maximum number of uses, etc.
One other thing I frequently do is rate-limit based on a curve. If I think 5 uses per minute is reasonable, for example, then after 5 uses in a minute from a session, each usage adds a delay of a fraction of a second * the number of uses in the last minute, squared, before the data is served.
The best answer would be to put this all behind a login system and secure that.
Assuming that you are using OAuth kind of system, In that case, make use of Access Token Mechanism that provides access to private API/User's data on behalf of User(Client) without exposing his/her credentials or API Key(Authentication key), also the access token can be expired based on the time/usage.
Example: The access token is generated against a single endpoint that can be the Html Conversion endpoint and will be expired once the action completion.
https://auth0.com/docs/tokens/access-token
And following blog post would be helpful to architect your authentication system
https://templth.wordpress.com/2015/01/05/implementing-authentication-with-tokens-for-restful-applications/
there is no good way to do front-end secure storage but my recommendation is :
is an API that used HMAC signing of requests in combination with OAuth authentication. The API key is actually a signing key. they key does not get transferred. The API key can still get found on the front-end but it becomes useless because you still need the OAuth token to send a valid request.
i know users will have to login in, but you can see this as an advantage because atleast you can log who is using the app by getting information from oauth.
please consider back-end secure storage!
You can use JWT tokens in my opinion. On the basis of username, password or any other info you can generate unique jwt tokens for different users.
Anyone can decipher these jwt tokens but not he unique security token.
If you want to add more more security to tokens, use JWE, encrypted web tokens.
More about these schemes can be found at https://medium.facilelogin.com/jwt-jws-and-jwe-for-not-so-dummies-b63310d201a3
Hashing is a decent option and should be done anyway, but for a fully secure method that wouldn't add too much complexity, you could simply abstract away from the authorization/API key by building your own API to interface with the API. This way you could both limit the kinds of things that can be done with the API key and also completely obscure the API key from the user
I don't think you should always go for user auth or JWT, it just doesn't fit all use cases. The idea of using a Captcha is interesting but also somewhat complex.
If complexity is not an issue I would rather use an infrastructure approach, I'm most familiar with AWS so I'll focus on that. Assuming you can change the host of your front end you can have your site hosted on an S3 bucket, served through a CDN, and create a proxy Lambda function that will hold the logic to call your API and store the API key as an encrypted environment variable. This Lambda you call through an API Gateway that can only be called by a specific IAM role which the S3 bucket also uses. You can also use a Cognito User Pool without authentication.
Going back to a simpler alternative the Captcha approach can be implemented as an attestation provider. I know of two services that do this, Firebase and KOR Connect. Due to Firebase using this approach only for their own resources as of the time of this writing I much rather use KOR Connect as it’s a very simple middleware that basically solves this issue. I won't go into detail about these services as it’s not the main concern of this topic but you can check the documentation their respective links.

Authenticating Requests From A Single Server

I'm working on a project which contains data belonging to multiple clients, and I'm trying to find a secure way to notify their servers of certain sensitive changes to their data.
The issue is that the most secure method I found for this is OAuth, but since my server will be pushing the updates to them, that would mean that each client would have to implement an OAuth provider solely to authenticate my server, and it feels like a bit of an overkill.
My question is: Keeping in mind that not all clients will use HTTPS, would it be enough to simply use a shared secret, a timestamp, and some form of encryption for their servers to safely receive and validate my updates or will that leave them vulnerable to attacks?
Yes, that would be secure. For simple messages I think JTW would be a very good choice. You could use it for just authentication or the actual notification itself. A few reasons you might want to use it:
It's signed, so you know the message hasn't been tampered with.
You can encrypt with public/private key pairs.
You can add any data you like.
It's very simple to implement and doesn't require back-and forth exchange between servers like OAuth often does.

REST API and API KEY

Please someone explain me how to use an api key and what is it good for.
I have searched a lot about this and I got different and conflicting answers. One says that an API key is kept secret and its never sent as the part of the communication, while others send it to the client without any encryption. What is the client's signature? How can he generate it and what can do the server with it? Why should monkeying with api keys instead of using the good old username-password pair? Could someone explain me how the communications look between a client (Android device) and the server (php api) in detail.
I'd appreciate any good tutorials, code samples, and explanations for beginners.
The topic of API authentication is a complex one. Below I'm going to do my best to explain one part of the issue: why is an API key better than a username / password?
Here we go.
When building (or working with an API), a common question developer's ask is "Why does this service require an API key instead of my username and password?" It's a great question!
First, let's talk about what API keys typically are.
API keys are usually randomly generated strings of letters and numbers. Furthermore, an API key typically comes in two parts: an ID and a secret. If you're using a web service like Stormpath, for instance, you might have two API keys that look like this:
API_KEY_ID=kzjbOg3iOm4k4MRpBss76yxlZSPJtoOPaqxirsfX
API_KEY_SECRET=A8FnQWM7RpgGjU3sZjOUgMIq5t8mvAhQES9iE30S
You can think of an API key ID as a username. This is a globally unique identifier which allows the API service to find your account.
You can think of an API key secret as a password. This is a password that, when matched up with the correct API key ID, will grant you access to the API service in question.
The main reason you WOULDN'T want to use a username and password to authenticate against an API is that:
Even if the API is served over SSL, there are many exploits available which can compromise your credentials. If you used your username / password to log into API services, and an attacker grabs these credentials, they have access to your account as a whole.
If you use your username / password to authentication against an API, what happens if one of your servers / API clients is compromised? This means you need to reset your username / password and update it for all of the clients which are using it. This can be time consuming, and costly.
By using a username / password, you're usually restricting yourself to a certain type of API usage. By having API key pairs, you're able to separate out API credentials to different levels of access (maybe on key pair can only access certain data, while another can access other types of data).
API key pairs are, in general, a much better idea. In addition to the obvious security benefits, they also serve other purposes:
If an API key pair is leaked, you can usually create / cycle API key pairs without needing to update every single client you own.
You can use API key pairs to provide sub-account functionality for your API.
Hope that helps!
have a look at this
REST authentication and exposing the API key
Why do some API providers require an API key?
And study a lil about Oauth

How exactly to implement challenge-response for REST API authentication?

I want my REST API server to be able to communicate only with my iOS app. The user base is going to be no more than 1000 people, and the market is pretty small and unpopular in general. That's why I think anything beyond a simple challenge-response authentication (HTTP, OAuth 2.0, SSL) would be an overkill. But I'm not sure exactly how this auth should flow. Here is what I have in mind:
Client app (user) sends a request: api.example.com/auth?username=john
Server responds with a randomly generated string: "somerandomlygeneratedstring"
Client takes the string, appends it to the username and then appends a secret string, hard coded in the app and uses MD5 to hash the entire string.
Client passes the string to the server: api.example.com/auth?username=john&response=thenewMD5hashstring
Server generates the same MD5 hash string and if they match, marks this user as authenticated in the database and all API requests from this user will be handled from now on.
Do I have the right idea? Or am I totally wrong? Please have in mind, I want basic security, anything too fancy would be an overkill for such a small project.
Also, I'm not keeping any sensitive data on my database like personal information.
You should simply use HTTP Basic auth for every request, through the Authorization header, and have all your interactions over SSL. If you want basic security, there's no need to go beyond that.
There are several problems with the scheme you have in mind.
Your last step is essentially a server-side session, which isn't acceptable in REST.
MD5 is effectively broken and shouldn't be used for anything but integrity checking.
In REST, you should use the standardized authentication method provided by the protocol if it fits your needs. Reinventing it to use URI parameters like you have in mind is unnecessary.
The hashing scheme you have in mind only makes sense when you want to sign the request, guaranteeing it wasn't tampered with.

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.