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.
Related
I know CURL & HTTP authentication to allow API calls only from certain requests.
I have something like this
www.mysite.com/list
www.mysite.com/api
list page calls the api page using jQuery Ajax post request and api page echos jSON response.
I am already checking HTTP referrer to verify Post requests come from certain origins but these requests can be forged.
I cannot use $_SERVER['remote_addr'] as this will check the client ip not the source ip of the API request.
As both the pages are hosted in the same web server and in the same hostname, its not possible to restrict based on hostname or IP address.
I am aware of some alternatives like
cURL with HTTP Authentication.
Encryption of jSON response and Decrypting before printing.
But is there any way to restrict these API pages to securely block access from outside the server or hostname?
Assuming you want to restrict access to "Joe Random user who is visiting your website with a web browser".
Not really.
There's no way to reliably determine that the client is a regular web browser. Anyone writing some other client to access your API can easily have it visit your website and get whatever tokens they need to prove that.
The best you can do is some sort of heuristic approach that looks for unusual traffic patterns (such as unusually high numbers of similar requests from one source, or ones which have very stable intervals between requests). You'll get false positives and negatives from that kind of approach though.
I may be wrong, but I think you are trying to invent csrf tokens. But with little modification:
You should store generated token in session/cookie before rendering /list. I am not sure whether jQuery send session/cookie with ajax request by default, but I think it should not be a big problem if not, to append it.
When you will process /api request you should validate cookie/session also for the token existance.
I have a hybrid WordPress plugin that fetches all data using curl from the main server. Let's call it A.
B is the client that requests for data and also can send data to A.
Now every request is encrypted and authenticated using a API access keys.
But the problem here is if I copy the plugin from B to a new client site C, the moment I use the same access keys etc. the plugin starts working.
I want to be able to restrict the access of one API access key to one domain name. How can I attain that?
I'd say to include the allowed host's IP address (B) in your access key administration.
So: when B does a call, you can validate the key and the IP it's calling from.
On A, you can use something like $_SERVER['REMOTE_ADDR'] to test the IP calling the script.
Two downsides: when sites move servers, the plugin will stop working. And of course, people can still spoof their IP, so there is a way to get around this, but at least you make it a lot more complicated and probably not worth the hassle for most cases.
A suggestion by TJHX
Make it part of the license you give your customers. The honest ones will follow it, the dishonest ones will find a way to break your DRM. This is a problem technology can't really solve confidently, especially when with things like wordpress people can just see your code - By TJHX
I have also looked into a lot of options but the mere fact is that the user always has access to the code in the wordpress plugin and can easily make amendments to the CURL request Headers even if you encrypt it.
All we can do it add it in our Licenses.
In my plugin, there are iframes that will be loading the data on the frontend so I am going to accept the domain name when the user buys the plugin and will check the referrers to my iframe to sort this issue out.
Thanks a lot guys for your help.
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,
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.
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.