Distributing and using API-keys for web-applications - php

I have a web-application for which I'm building a Drupal module that allows my customers to access certain data on my application.
I intend to distribute secret API-keys to my customers who need to enter that value in their copy of the Drupal module. This Drupal module then talks to my web-application, but I need to make sure that the POST requests are indeed coming from that source.
How can this 'secret key' be used to pass some information that when my application receives it, it knows:
(a) its from that client's server.
(b) it hasnt been eavesdropped on / copied and used by someone else?
Should I be using this API-key as a password to encrypt some data that matches the rest of the POST request? When receiving it, I decrypt it using my copy of their API-key and it if matches the rest of the data, I consider it validated?
Is there a frame-work that does this for me? Something within Zend?

Use HTTPS and just send the API key in the request. It's that simple.
If you use HTTP then you are going to reinvent the wheel.
Update:
Here is an update after reading the comments, because in the question you didn't explain that you want to give the API keys to visitors of the website (in which case you would be screwed no matter what you do).
The comment by juanpaco explains what to do (and what I originally assumed that you're doing anyway) but I'll try to explained it in a little bit more detail.
The most important thing is that you don't use the API key in the web form. The API key is only used in the communication between your customers servers and your API server.
Here is a simplified explanation:
You give your customer a key and some software/module/library to install on his server.
When a visitor visits your customer's website he sees some HTML generated by your module that does not include any API key and can communicate only with your customer's server (with HTTPS if there is any sensitive information or user accounts involved at all).
Your module on the customer's server gets the request from the visitor.
Your module connects to your server using the API key (with HTTPS).
Your API server responds to the customer's server.
The customer's server responds to the visitor.
Your API key is never sent in the cleartext and never given to website visitor.
This is the only reasonable way to use API keys and after I first read your questions I assumed that you are concerned about the safety of sending your API keys between your servers and the servers of your customers.
If your customers were to give their keys to every visitor of their websites then those visitors would always be able to know them, no matter how hard you would try to make it. Giving visitors API keys and making them possible to use but impossible to read would be impossible. Not hard - impossible. No matter what protocols, encryption or anything you use.
(Thanks to juanpaco for bringing this old answer to my attention.)

Collect and store every client incoming url(e.g. www.authorisedclienturl.com) as part of the parameters you would store on your server before generating an API key to be shared with the client.
The client will use HTTPS to send the API key in the request boby from their registred authorised client urls only.
Use the API key to decript the client information on your server and retrieve the registered client url, verify that the incoming request url is present in the registered urls, then accept and proceed with other processes.

Related

How to secure webservice so that only my android app can use my webservice

We have built an android app that POST HTTP Request from Android to my PHP server.In response the webservice sends JSON object to android app to show results.
like one of the service is like
http://mydomain.com/test/weather.php?lat=13.4332&long=80.454
Since I am not expert in android so want to handle the security for webservice from PHP end.
How can I secure my webservice call so that only my app can use my webservice. I dont want if someone decrypt the apk and get the webservice URL and use it after customize the ouput data.
How can I achieve this? Please provide me any good example.
If you are able, you should implement the use of HTTPS in your app and this could solve many security problems.
Create a self-signed server SSL certificate and deploy on your web server with the keytool in the Android SDK for this purpose. Then create a self-signed client and deploy that within your application in a custom keystore included in your application as a resource (keytool will generate this as well). Configure the server to require client-side SSL authentication and to only accept the client certificate you generated.
oReilly : Application Security for the Android Platform
or
If it's only your client and your server, you can (and should) use SSL without purchasing anything. You control the server and the client, so each should only trust one certificate, the one belonging to the other and you don't need CAs for this purpose.PHP can receive data via POST or GET out of your site and even the internet browser. One of the methods used to do this is by curl.
You must verify the information received by POST or GET in your PHP, this language has much ability to solve these "problems"; Take a look at this part of the PHP official documentation.
Suppose you're building a login system: Also you can add in the login page place a hidden element with secret unique code that can happend only once, save this secret code in session, so, the loging script look in session for this code, compare with what was posted to the script, should same to proceed.
And, if you want to get the IP address of your visitors:
function getRealIpAddr()
{
if (!empty($_SERVER['HTTP_CLIENT_IP'])) //check ip from share internet
{
$ip=$_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) //to check ip is pass from proxy
{
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
$ip=$_SERVER['REMOTE_ADDR'];
}
return $ip;
}
you want want to look up here: Encrypt data within mobile app and send to web service and Web services: how prevent illegal accesses
Make sure you request in the POST request an extra field to check for sender's id. In this field you could use a hash sequence, like one generated by a md5 algorithm.
So, in your Android App you would generate hash string using an identifier and a general string, like so:
$identifier='Here comes an understandable unique Id for your App user';
$common_sequence='Here comes random sequence, the same to be used server-side';
$hash_sequence=crypt($identifier . $common_sequence);
In your POST you have 2 fields for this:
Hash_sequence
UserId
In your server you can re-generate the hash_sequence as you have common_sequence already, and also the userId. Check if they match.
This solution, however, has some weak points, specially the fact that one could use the hash_sequence several times. You could consider inserting a time factor to the generating sequence, for example, like yyyymmddHHmm so the sequence would change each minute.
Crypt() is a function that generates your hash_sequence in PHP. You would need however a way to generate a similar sequence in your App. In this case, a simple MD5 hash might be enough, and there must be a MD5 generator native in Android Dev language.
Best wishes,

php / apache, is there any way to block cross domain post

I have some ajax page with php post (so that CAPTCHA is not a good idea).
some fsockopen or curl could set POST value to steel data with cross domain.
So php / apache, is there any way to block cross domain post?
You are publishing the data. You can't stop people requesting it.
If you want to keep it secret, require authorisation before allowing access.
There are various barriers you can put in people's way—while still keeping the data public—but none of them are difficult to bypass. Testing the user agent doesn't stop the requestor specifying a user-agent that matches a common browser. Requiring a cookie from another page on your site doesn't stop them requesting that page and getting a cookie for their tool. Etc.
A lot web services that offer an API, but don't want just any old person to access the API, use public / private keys via CURL. You would have to do a little research on public / private key encryption if you are not familiar. I am sure there are PHP libraries that get all if not most of this done for you.
Credit card merchants like Authorize.net, and several customer database services that handle PII (Personally Identifiable Information) that I've worked with over the years allow you to post to a URL and retrieve the result. They protect their services using public / private key encryption. They issue me a key and I have to post that key along with my request data. The key is usually sent in a header, hence the need to use CURL.
Background Information:
http://computer.howstuffworks.com/encryption3.htm
PHP Examples:
http://www.joeldare.com/wiki/php:php_public_private_key_cryptography
Note: the benefit of this system is that you have absolute control over who is allowed to post to the PHP script on your server. If you don't need that level of control, you can just use something called "http basic auth". Place your sensitive scripts in a directory and protect it with .htaccess authentication. Here is a tool to get you started. http://www.htaccesstools.com/htaccess-authentication/
When you make requests via ajax (jquery, I take it) you can pass the login and password. Just make sure you use an SSL connection in your ajax (HTTPS). Otherwise, people can sniff out your login and password as it will be sent in plain text without the use of SSL.
If you do use basic auth instead of public/private keys, your domain will need an SSL cert if it does not already have one. You can buy one from someplace like Thawte.com (not cheap), or self-sign your own certificate. However, if you're going to go through all that trouble, you're 80% to the point of just going the public/private key encryption route. Self-signed certificates usually prompt the user's browser with a warning. This scares away a lot of people.

Handling working of PHP API key on webpage

i m building a phpapi and in this api will be giving my clients API key generated for each client.
So basically my client will be sending client id,his personal data(to be stored in DB) & an API key to my api.php page and this API key will be placed in a hidden field on clients form.
Now my doubt here is that this key can be seen by anyone if they view page source...
So how can i prevent key from being not seen so that no other clients can use it for them..
OR
Is there any other way to place API key on form so it cannot be seen and use securely..
Every data you send to your client can be viewed by him and others (Sniffers ;) ).
The only way to make the communication between him and you really secure is to use a HTTPS-Connection (=> SSL-Certificate!). Then it is nearly impossible for others to see the API-Key but the client himself will be able to see it in the source-code. If the client's pc has to know the key then the client will be always able to view it.
Would you be able to use php sessions? This way the api key stays on the server and coupled with https would provide great security.

Creating a PHP API: Checking from which server the API Request comes from

I'm creating a PHP API for a website and I'd want to restrict the API access to domains that are registered on our server (in order to prevent abusing of API usage). So, this is my approach right now, and well, it should look pretty good on paper.
The API is setup at api.example.com.
A user that wants to use the API registers with us, adds his domain and gets an API key.
The user of the API will use his API key to encrypt his request data (via mcrypt) and sends it, via cURL to api.example.com.
My server checks from which domain this API request comes from and matches that domain to an API key in the database. If there is an API key, the API decrypts the request via mcrypt with that key and then using the same method encrypts and sends the result.
I'm stuck on step 4. Originally, I planned to use HTTP_REFERER to check it, but since cURL doesn't send one by default and it could be easily faked in the user-side code (CURLOPT_REFERER as far as I remember), I am stuck here.
Is there a method to know from which domain this API request comes from? I see that it can be done with some popular APIs like the reCAPTCHA one. Checking the _SERVER["REMOTE_HOST"] isn't really an option because of shared hosts (they have the same IPs) so this would not be able to prevent abuse (which would originate mostly from shared servers anyway).
Is there such a method to check for it? Thanks!
#Shafee has a good idea it just needed some tweaking. We're focusing on the visible part of the API call, which is the API key. This is visible in the URL and tells the API who is requesting the data. Rather than trying to prevent others from stealing this key and running their own cURL call with the domain they intercepted it from, we can 'just add' another key to the mix, this one not visible to those interceptors. I'm not saying stop checking where the request is coming from, it's still a good way to kick out invalid requests early on in the script, but with a second key, you guarantee that only the person requesting the data actually knows how to get the data (you're trusting them not to give it away to anyone).
So, when the user registers for a key, you're actually assigning two different keys to the user.
API_KEY - The public key that connects you to your domain. The system looks up the domain and key provided in order to find the next key.
MCRYPT_KEY - This is the key that will be used to actually encrypt that data via Mcrypt. Since it's encrypted data, only the requester and the server will know what it is. You use the key to encrypt the data and send the encrypted input with your API key to the server, which finds the key that it needs to decrypt that input via the API key and domain (and IP) that have been provided. If they did not encrypt the data with the proper key, then decrypting with the correct key will return gibberish and the json_decode() call will return NULL, allowing the script to simply return an 'invalid_input' response.
Ultimately with this method, do we even need to check where (domain/IP) the request is coming from? Using this method it really comes down to the API users not giving away their API/MCRYPT key pair to other users, similar to not giving away your username/password. Even so, any website can easily just go sign up to get their own key pair and use the API. Also to note, the API will not even return anything useful to their server unless the user on their end logs in using the correct username and password, so their end will already have that information. The only thing new our server is really returning is their email address upon successful validation of the user. Having said that, do we even need to use cURL? Could we not simply use file_get_contents('http://api.example.com/{$API_KEY}/{$MCRYPT_DATA}')? I realize I'm asking more questions in my answer...
You can varify what ip the request comes from, and you ofen can do a ptr search to get a domain name for that ip, but probely the ip adress have more then one domain, and you end up whit the wrong one, so i recomendate that the client send his domainname in the reques, maybe whit HTTP_REFERER, and that you make a dns check if that domain points to the ip asking for it, but notice that a domain, like google.com, can point to more then one ip.
(the ip could probely be faked to, whit some good hacking skill, but thats out of my knowledge)
How about introducing a second variable like lets say an app id. When a user registers her domain, associate this id with the domain. The user needs to submit the app id with each request without encryption along with the encrypted api call. Then you can look up the app id get the app secret and try to decrypt?
In order to best prevent abuse of your API, limit either the speed of requests, or limit the number of requests they can make. If someone is stupid and shares their API key, they'll only be limiting their own API usage, making it more economical for people who intend on abusing the API to get their own key.
Plus, what if someone decides to implement a desktop application using your API? Surely they won't require their users to send their IP addresses to them so that they can whitelist them?
Also, you can combine limiting speed/limiting requests, and limit speed based on the number of requests like how Verizon limits the speed of their 3G network if you pass a certain amount of data usage.

How do you verify an API request came from a certain domain?

I have a web API that I want to allow any domain to submit data to. However, to keep bogus spam down I want to find some way to insure that a request stating it's from a certain domain actually is from that domain and that someone isn't trying to trick me by posting on another domains behalf.
For example, if http://example.com submits some data - thats good. If script kiddie #237 submits data claiming to be example.com - that's bad.
At first I was going to use a secret key system to HMAC sign each request - but signup is going to be open, free, and automated for this API. I'm not sure how I could tell if PersonA or PersonB really owns http://example.com and deserves the API key.
Provide a key file that they will have to upload on that domain. And you check the existence and valid data against your internal database.

Categories