I've read a lot about .htaccess rules, checking headers, using encryption etc.. but I haven't found exactly the answer I'm after. I know that assuming the server is set up right, you can't access my precious PHP scripts with AJAX. I tried checking if an access variable was defined which disallowed address bar access but also blocked my AJAX requests.
If I have some PHP scripts that I use for AJAX calls, is there a way that I can prevent address bar access, PHP POST (cURL etc) as well as AJAX from outside my domain (assumed via cross-domain access restrictions) ?
There is NO way absolutely to safely/reliably identify which part of the browser the request comes from -- address bar, AJAX. There's a way to identify what is sending though browser/curl/etc via User-Agent header (but not reliably)
A quick but a lot less reliable solution would be to check for the following header. Most browsers attach it with AJAX calls. Be sure to thoroughly look into it, and implement.
X-Requested-With: XMLHttpRequest
NOTE: Do not trust the client if the resource is cruicial. You are better off implementing some other means of access filtering. Remember, any one can fake headers!
You can check whether the request isn't an Ajax request and forbid it, but it's not really safe due to the fact that the headers can be manipulated.
What you can do is to block every IP except the IP which is allowed to access those files.
What can do either is do implement a kind of authentication, where external applications have to send credentials to your script and the scripts checks if the client is valid.
Many ways, but they're all not really the best ways to achieve maximum security.
I do not know definitely. However – indirectly, you can do this. Pass a unique and constantly changing parameter (GET or POST) that only you have access to as proof of the origin. If the request lacks this unique variable, then its not from you. Think outside the box on this one. Could be anything you want, here are some ideas.
1) pass the result of a mathematical equation as proof of origin. Something that you can programmatically predict, yet not obvious to prying header hackers. i.e cos($dayOfYear) or even better base64_encode(base64_encode(cos($dayOfYear))).
2) store a unique key in a database that changes every time someone access the page. Then pass that key along with the request, and do some checks on the end page, if they dont match up to the database key, you've found the peeping tom. (note there will be logic involved for making sure the key hasn't changed in between transmission of requests)
etc..
Try to catch if isset SERVER['HTTP_ORIGIN'] from the POST access, it must be identical to your domain. If so, then the POST is generated by yourselft website and it's safe to process it.
Related
I asked a similar question before, and the answer was simply:
if JavaScript can do it, then any client can do it.
But I still want to find out a way do restrict AJAX calls to JavaScript.
The reason is :
I'm building a web application, when a user clicks on an image, tagged like this:
<img src='src.jpg' data-id='42'/>
JavaScript calls a PHP page like this:
$.ajax("action.php?action=click&id=42");
then action.php inserts rows in database.
But I'm afraid that some users can automate entries that "clicks" all the id's and such, by calling necessary url's, since they are visible in the source code.
How can I prevent such a thing, and make sure it works only on click, and not by calling the url from a browser tab?
p.s.
I think a possible solution would be using encryption, like generate a key on user visit, and call the action page with that key, or hash/md5sum/whatever of it. But I think it can be done without transforming it into a security problem. Am I right ? Moreover, I'm not sure this method is a solution, since I don't know anything about this kind of security, or it's implementation.
I'm not sure there is a 100% secure answer. A combination of a server generated token that is inserted into a hidden form element and anti-automation techniques like limiting the number of requests over a certain time period is the best thing I can come up with.
[EDIT]
Actually a good solution would be to use CAPTCHAS
Your question isn't really "How can I tell AJAX from non-AJAX?" It's "How do I stop someone inflating a score by repeated clicks and ballot stuffing?"
In answer to the question you asked, the answer you quoted was essentially right. There is no reliable way to determine whether a request is being made by AJAX, a particular browser, a CURL session or a guy typing raw HTTP commands into a telnet session. We might see a browser or a script or an app, but all PHP sees is:
GET /resource.html HTTP/1.1
host:www.example.com
If there's some convenience reason for wanting to know whether a request was AJAX, some javascript libraries such as jQuery add an additional HTTP header to AJAX requests that you can look for, or you could manually add a header or include a field to your payload such as AJAX=1. Then you can check for those server side and take whatever action you think should be made for an AJAX request.
Of course there's nothing stopping me using CURL to make the same request with the right headers set to make the server think it's an AJAX request. You should therefore only use such tricks where whether or not the request was AJAX is of interest so you can format the response properly (send a HTML page if it's not AJAX, or JSON if it is). The security of your application can't rely on such tricks, and if the design of your application requires the ability to tell AJAX from non-AJAX for security or reliability reasons then you need to rethink the design of your application.
In answer to what you're actually trying to achieve, there are a couple of approaches. None are completely reliable, though. The first approach is to deposit a cookie on the user's machine on first click, and to ignore any subsequent requests from that user agent if the cookie is in any subsequent requests. It's a fairly simple, lightweight approach, but it's also easily defeated by simply deleting the cookie, or refusing to accept it in the first place.
Alternatively, when the user makes the AJAX request, you can record some information about the requesting user agent along with the fact that a click was submitted. You can, for example store a hash (stored with something stronger than MD5!) of the client's IP and user agent string, along with a timestamp for the click. If you see a lot of the same hash, along with closely grouped timestamps, then there's possibly abuse being attempted. Again, this trick isn't 100% reliable because user agents can see any string they want as their user agent string.
Use post method instead of get.Read the documentation here http://api.jquery.com/jQuery.post/ to learn how to use post method in jquery
You could, for example, implement a check if the request is really done with AJAX, and not by just calling the URL.
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
// Yay, it is ajax!
} else {
// no AJAX, man..
}
This solution may need more reflexion but might do the trick
You could use tokens as stated in Slicedpan's answer. When serving your page, you would generate uuids for each images and store them in session / database.
Then serve your html as
<img src='src.jpg' data-id='42' data-uuid='uuidgenerated'/>
Your ajax request would become
$.ajax("action.php?action=click&uuid=uuidgenerated");
Then on php side, check for the uuid in your memory/database, and allow or not the transaction. (You can also check for custom headers sent on ajax as stated in other responses)
You would also need to purge uuids, on token lifetime, on window unload, on session expired...
This method won't allow you to know if the request comes from an xhr but you'll be able to limit their number.
In simplest terms, I utilize external PHP scripts throughout my client's website for various purposes such as getting search results, updating content, etc.
I keep these scripts in a directory:
www.domain.com/scripts/scriptname01.php
www.domain.com/scripts/scriptname02.php
www.domain.com/scripts/scriptname03.php
etc..
I usually execute them using jQuery AJAX calls.
What I'm trying to do is find is a piece of code that will detect (from within) whether these scripts are being executed from a file via AJAX or MANUALLY via URL by the user.
IS THIS POSSIBLE??
I've have searched absolutely everywhere and tried various methods to do with the $_SERVER[] array but still no success.
What I'm trying to do is find is a piece of code that will detect (from within) whether these scripts are being executed from a file via AJAX or MANUALLY via URL by the user.
IS THIS POSSIBLE??
No, not with 100% reliability. There's nothing you can do to stop the client from simulating an Ajax call.
There are some headers you can test for, though, namely X-Requested-With. They would prevent an unsophisticated user from calling your Ajax URLs directly. See Detect Ajax calling URL
Most AJAX frameworks will send an X-Requested-With: header. Assuming you are running on Apache, you can use the apache_request_headers() function to retrieve the headers and check for it/parse it.
Even so, there is nothing preventing someone from manually setting this header - there is no real 100% foolproof way to detect this, but checking for this header is probably about as close as you will get.
Depending on what you need to protect and why, you might consider requiring some form of authentication, and/or using a unique hash/PHP sessions, but this can still be reverse engineered by anyone who knows a bit about Javascript.
As an idea of things that you can verify, if you verify all of these before servicing you request it will afford a degree of certainty (although not much, none if someone is deliberately trying to cirumvent your system):
Store unique hash in a session value, and require it to be sent back to you by the AJAX call (in a cookie or a request parameter) so can compare them at the server side to verify that they match
Check the X-Requested-With: header is set and the value is sensible
Check that the User-Agent: header is the same as the one that started the session
The more things you check, the more chance an attacker will get bored and give up before they get it right. Equally, the longer/more system resources it will take to service each request...
There is no 100% reliable way to prevent a user, if he knows the address of your request, from invoking your script.
This is why you have to authenticate every request to your script. If your script is only to be called by authenticated users, check for the authentication again in your script. Treat it as you will treat incoming user input - validate and sanitize everything.
On Edit: The same could be said for any script which the user can access through the URL. For example, consider profile.php?userid=3
I have a javascript on my webpage which makes a call to a php file and passes some values to the php file. How can i know for sure that the call to the php file was from the js on my webpage and not directly entering the php url from the browsers address bar?
You'll want to use check if $_SERVER['HTTP_X_REQUESTED_WITH'] is XMLHttpRequest. That will prevent people from directly typing the URL in their browsers while allowing Ajax requests.
if ( ! empty($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' )
{
// Do something useful
}
You might want to see Do all browsers support PHP's $_SERVER['HTTP_X_REQUESTED_WITH']? for an explanation of what browsers/JavaScript libraries send the HTTP_X_REQUESTED_WITH header.
you can use the following info:
The headers that are being sent (usually Ajax calls adds special headers)
X-Requested-With: XMLHttpRequest
refering URL in the $_SERVER
Both can be hacked though.
If you need a very safe solution, you need to create a unique code for each request and send it to the server from your JS. This code needs to change after each time it is used.
You can't. Anything you expose to ajax you expose to the world. What's more is that someone wanting to get into that page could just run their own javascript on the page anyway and spoof any HTTP headers they want. These are the people you presumably want to keep out anyway. You shouldn't use measures that will limit non-malicious users but provide relatively little, if any, trouble to malicious users.
That said, I have never heard of HTTP_X_REQUESTED_WITH and based on preliminary reading it's not a good idea to use. I usually use POST and check that the _SERVER[REQUEST_METHOD] is POST because most modern browsers will use GET for any requests made by the url bar (that's my experience anyway). Again, this is not to keep bad people out, it's just to prevent accidents.
Another measure you should take is to check that a flag is sent to the page to help signal it's coming from a verified source. Depending upon how secure the ajax page is supposed to be, you may also want to verify session, etc. A somewhat safe way is to create a unique hash (e.g. md5) and store it in the DB with a timestamp. That hash indicates the page can be visited, say, up to three times. When the user clicks your ajax link, it sends the hash. The hash is flagged as consumed and cannot be reused. The hash should also go stale some time after creation (5 minutes? It depends and it's up to you).
Finally, make sure that this page is ignored by friendly robots (robots.txt, meta if possible, etc.). This will prevent people reaching it accidentally via search engines.
I have several pages that call in content via jQuery .ajax. I dont want the content visible on the page so thats why I went with .ajax and not showing/hiding the content. I want to protect the files inside the AJAX directory from being directly accessible through the browser url. I know that PHP headers can be spoofed and dont know if it is better to use an "access" key or try doing it via htaccess.
My question is what is the more reliable method? There is no logged on/non logged user status, and the main pages need to be able to pull in content from the pages in the AJAX directories.
thx
Make a temporary time-coded session variable. Check the variable in the php output file before echoing the data.
OR, if you don't want to use sessions.. do this:
$key = base64encode(time().'abcd');
in the read file:
base64decode
explode by abcd
read the time. Allow 5 seconds buffer. If the time falls within 5 seconds of the stamped request. You are legit.
To make it more secure, you can change your encrypting / decrypting mechanism.
I would drop this idea because there is no secure way to do it.
Your server will never be able to tell apart a "real" Ajax request from a "faked" one, as every aspect of the request can be forged on client side. An attacker will just have to look into a packet filter to see what requests your page makes. It is trivial to replicate the requests.
Any solution you work out will do nothing but provide a false sense of security. If you have data you need to keep secret, you will need to employ some more efficient protection like authentication.
Why not have the content be outside the webserver directory, and then have a php script that can validate if the person should see it, and then send it to them.
So, you have getcontent.php, and you can look at a cookie, or a token that was given to the javascript page and it uses to do the request, and then it will just fetch the real content, set the mime types and stream it to the user.
This way you can change your logic as to who should have access, without changing any of the rest of your application.
There is no real difference to having http://someorg.net/myimage.gif and http://someorg.net/myscript.php?token=887799&img_id=ddtw88 to the browser, but obviously it will need to work with GET so a time limited value is necessary as the user can see reuse it.
How to detect anonymous user like facebook does, when you open it throught proxy websites like hidemyass.com. I think its something related to proxy, but beyond I dont know anything about it, but I want to create that.
Most common way to detect proxy servers is by looking if these http headers fields are empty (if not, a proxy is used to access you're webserver):
HTTP_FORWARDED
HTTP:X-Forwarded
HTTP:Forwarded-For
HTTP:X-Forwarded-For
In PHP you can read these values with the getenv() function.
It is hard to say who is trying to hide his identity and who has limited/restricted access based on firewall rules etc. You can also check if user accept COOKIES by sending special token on first request and fetching on second.