Deny access to public php from browser but allow application use - php

Hello all please help the ignorant. Ive searched high and low to find a solution but it seems to have evaded me.
I have recently set up a php file containing a read all script in the public html folder on my host. The db_config and db_connect and any more sensitive files are happily hidden away so direct access is not possible.
I need to prevent or at least slow down the average Joe from being able to run my read all script in their browser, obviously with the time taken to collect such a database it has become somewhat valuable and would hate to let someone have it for free too easily.
The php needs to be accessible for an mobile application to execute so unfortunately has to stay in the public directory (unless you know otherwise?)
Can you please point me in the right direction?
Header redirects seem to be the only option available. Which i must admit confuse me on the scripting somewhat.
As much as Id love someone to just give me the script, wheres the fun in not learning it yourself :)
Thank you for taking the time to read and reply.

I'll ignore CHMOD in this answer:
This isn't the best solution, but an easy-to-maintain method of protecting the file would be to block public access to it using HTACCESS (if you can). Using a flag like one of the other answers mentions is good too and is also a legitimate way to do this, but HTACCESS would disallow the script from even running in the first place.
<files myfile.php>
order allow,deny
deny from all
</files>
Edit: Just saw that you mentioned JSON so ignore the above in this case (I am not familiar with JSON, but I don't think it would work).
This solution isn't perfect either, but it could help a little:
PHP check whether Incoming Request is JSON type
You can detect if the incoming request is from JSON and then ignore if it isn't.

as I understand, Your app needs to use it, but not anyone on the web, right? You could do a few things.
First, your app could request the page with a query string like &verified=1 and unless that $_GET variable is passed, the script wouldn't work. Like
if(isset($_GET['verified'])){
//show code
}
else
{
//not today average joe
}
You could also put it in a secret directory like "sjdvjhb_kdfjgvkedn"

Related

PHP - Allow access from only one domain

I have kind of a strange situation right now. Basically, my company is currently putting links to the latest builds of our software behind a gate, but once the user signs in, they can distribute the link to the builds. Free 30-day trials, unaccounted for.
So I would like to block access to URL /downloads/file.extension, or even just /downloads/ entirely, unless the referring URL is allowed_domain.com.
I would love to use .htaccess, but the hosting provider (WP Engine) we use has their servers set up on Nginx. Not only that, but I have to send my Nginx code to WP Engine for them to implement for me, which is not practical.
Thus, I am looking for a PHP ONLY solution, or a WordPress plugin that I apparently didn't notice.
And yes, I know this is a really stupid way for my company to be storing important files, but I need to fix this now until they come up with a better way.
You could use this method that I'm using it.
Enjoy.
You're going to need to list down those IP address.
<?php $allow = array("201.168.0.1", "456.789.123", "789.123.456"); //allowed IPs
if(!in_array($_SERVER['REMOTE_ADDR'], $allow) && !in_array($_SERVER["HTTP_X_FORWARDED_FOR"], $allow)) {
header("Location: http://yourdomain.com/index.php"); //redirect
exit();
} ?>
Unfortunately it is not possible to do what you described. That is because when someone tries to access a file from the site, the web server will first check if it exists and if it does, it will serve the file immediately. It does not go through any PHP code. Therefore you cannot write any PHP code that will intercept this request and block it.

Make a Linux user able to include PHP code but not able to view it?

User A has some PHP library files. User B needs access to the library. Is it possible permission-wise to make user B able to include the PHP file but not able to view the source code?
User A library entry file is lib.php.
User B uses lib.php in his start.php like this:
include path/to/lib.php;
However user B won't be able to view the content of lib.php or any other class files thereof.
Is this possible?
You're trying to find a way to do something that can't be done properly. Maybe in a kind of hackish, definitely dirty way.
You really should consider writing an API for your Application that contains all your logic. Then you could just handle everything else with User permission and so on, perfectly clean and state of the art.
Nobody but the API devs can look into the code, but everyone can use it based on his user permissions.
Every other method could is just to hard to handle and will cause more problems than just writing an API. It's worth the time.
Basically what you ask is not possible. The PHP interpreter needs to be able to read the file in order to include it, and if the PHP process can read it then your untrusted user can write some code that would read it in and dump it back out.
A few options you have are:
1) Use an API. Would allow you to keep you code secret as you'd only expose the API. Might take a few days work to implement though (or might not even be possible - impossible to say without knowing what you are doing), so probably not suitable in your situation.
2) Obsfucate your code. There are a number of PHP code obsfucators out there. It wouldn't stop prying eyes completely but it might be enough for your purposes.
3) Create a stub include file. If what your library includes isn't all critical to the running of the code you could create a cut-down stub library for your client to code against, then replace it with the real thing when they've done.

How to secure sensitive PHP files that process Jquery data?

On my website, I have a search.php page that makes $.get requests to pages like search_data.php and search_user_data.php etc.
The problem is all of these files are located within my public html folder.
Even though someone could browse to www.mysite.com/search_user_data.php, all of the data processed is properly escaped and handled, but on a professional level this is inadequate to even have this file within public reach.
I have tried moving the sensitive files to my web root, however since Jquery is making $.get requests and passing variables in the URL, this doesn't work.
Does anyone know any methods to firmly secure these vulnerable pages?
What you describe is normal.
You have PHP files that are reachable in your www directory so apache (or your favored webserver) can read and process them.
If you move them out you can't reach them anymore so there is no real option of that sort.
After all your PHP files for AJAX are just regular php files, likely your other project also contains php files. Right ? They are not more or less at risk than any script on your server.
Make sure you program "clean". Think about evil requests when writing your php functions, not after writing them.
As you already did: correctly quote all incoming input that might hit a database or sensitive function.
You can add security checks on your incoming values and create an automated email if you detect someone trying evil stuff. So you'll likely receive a warning in such cases.
But on the downside: You'll regularly receive warnings because some companies automatically scan websites for possible bugs. So you will receive a warning on such scans as well.
On top of writing your code as "secure" as you can, you may want to add a referer check in your code. That means your PHP file will only react if your website was given as referer when accessing it. That's enough to block 80% of the kids out there.
But on the downside: a few internet users do not send a referer at all, some proxies filter that. (I personally would ignore them, half the (www) internet breaks on them anyway)
One more layer of protection can be added by htaccess, you can do most within PHP but it might still be of interest for you: http://httpd.apache.org/docs/2.0/howto/htaccess.html
You can store a uid each time your page is loaded and store it in $_SESSION['uid']. You give this uid to javascript by doing :
var uid = <?php print $_SESSION['uid']; ?>;
Then you pass it with your get request, compare it to your $_SESSION :
if($_GET['uid'] != $_SESSION['uid']) // Stop with an error message or send a forbidden header.
If it's ok, do what you need.
It's not perfect since someone can request search.php and get the current uid, and then request the other pages, but it may be the best possible solution.

PHP odd variable Question. Pertaining to "Root"

Ok I get a script from: http://abeautifulsite.net/blog/2008/03/jquery-file-tree/
Its a directory listing script. I am having troubles with it. It works out of the box no problems per say other than the put fact that it goes way back into the system structure then I am allowed to even see some how.
The person that made the script has this one line that throws me off and I can't make heads of tales of it per say.
file_exists($root . $_POST['dir'])
I've never seen $root in that context before. Nor is it defined anywhere in the script from what I can tell. So is that a valid thing? If not can anyone tell me how I can use this script beneficially to just displaying directories starting at a specific directory. The document I point to with the above link shows an example, but it doesn't seem to mean anything to the scripts workings.
On the other hand if someone knows of a canned script thats very similar in nature I'd be happy to give that a look too. But I'd really like to edit this one to work the way I want it to work so any help would be appreciated.
an example of how far its going back can be found at http://domainsvault.com/tree/
I say its going far back because I don't even have access to those directories through my ftp.. its a shared system.. hostgator..
*EDIT* Thanks Everyone for the input, this essentially what I was afraid of hearing. It was hopped that we could skip reinventing the wheel by using this concept. But its appearing more so than not that its basically a bricked concept and far from worth using and attempting to tamper with. It'd likely be a lot more easy for me to build something from scratch than have to deal with this. This was just one of those canned scripts you find it looks ascetically pleasing to the eye, and you hope for the best. Didn't turn out to be the case, thanks again all.
file_exists($root . $_POST['dir'])
Run away.
This connector script does no checking on what paths you pass to it, so it's perfectly possible to escape the root (which, yes, you're supposed to set manually) and browse any files on your server that the web user has access to.
Also, it fails to do URL-escaping, and mangles Unicode through inadvisable use of htmlentities. This will make files with various punctuation or non-ASCII characters in fail.
This is a shonky and insecure script. Do not deploy it.
$root is a user-defined variable. It should be defined somewhere in the script - it may be a global. The script can still work if the variable doesn't exist (it might have been deleted in a previous code refactor), in that case you should just delete the variable from the line you copied here.
I think $root means $_SERVER[ 'DOCUMENT_ROOT']
you can defined as
$root=$_SERVER[ 'DOCUMENT_ROOT']
at the beginning

No require, no include, no url rewriting, yet the script is executed without being in the url

I am trying to trace the flow of execution in some legacy code. We have a report being accessed with
http://site.com/?nq=showreport&action=view
This is the puzzle:
in index.php there is no $_GET['nq'] or $_GET['action'] (and no
$_REQUEST either),
index.php, or any sources it includes, do not include showreport.php,
in .htaccess there is no url-rewriting
yet, showreport.php gets executed.
I have access to cPanel (but no apache config file) on the server and this is live code I cannot take any liberty with.
What could be making this happen? Where should I look?
Update
Funny thing - sent the client a link to this question in a status update to keep him in the loop; minutes latter all access was revoked and client informed me that the project is cancelled. I believe I have taken enough care not to leave any traces to where the code actually is ...
I am relieved this has been taken off me now, but I am also itching to know what it was!
Thank you everybody for your time and help.
There are "a hundreds" ways to parse a URL - in various layers (system, httpd server, CGI script). So it's not possible to answer your question specifically with the information you have got provided.
You leave a quite distinct hint "legacy code". I assume what you mean is, you don't want to fully read the code, understand it even that much to locate the piece of the application in question that is parsing that parameter.
It would be good however if you leave some hints "how legacy" that code is: Age, PHP version targeted etc. This can help.
It was not always that $_GET was used to access these values (same is true for $_REQUEST, they are cousins).
Let's take a look in the PHP 3 manual Mirror:
HTTP_GET_VARS
An associative array of variables passed to the current script via the HTTP GET method.
Is the script making use of this array probably? That's just a guess, this was a valid method to access these parameter for quite some time.
Anyway, this must not be what you search for. There was this often misunderstood and mis-used (literally abused) feature called register globals PHP Manual in PHP. So you might just be searching for $nq.
Next to that, there's always the request uri and apache / environment / cgi variables. See the link to the PHP 3 manual above it lists many of those. Compare this with the current manual to get a broad understanding.
In any case, you might have grep or a multi file search available (Eclipse has a nice build in one if you need to inspect legacy code inside some IDE).
So in the end of the day you might just look for a string like nq, 'nq', "nq" or $nq. Then check what this search brings up. String based search is a good entry into a codebase you don't know at all.
I’d install xdebug and use its function trace to look piece by piece what it is doing.
EDIT:
Okay, just an idea, but... Maybe your application is some kind of include hell like application I’m sometimes forced to mess at work? One file includes another, it includes another and that includes original file again... So maybe your index file includes some file that eventually causes this file to get included?
Another EDIT:
Or, sometimes application devs didn’t know what is a $_GET variable and parsed the urls themselves -> doing manual includes based to based urls.
I don't know how it works, but I know that Wordpress/Silverstipe is using is own url-rewriting to parse url to find posts/tags/etc. So the url parsing maybe done in a PHP script.
Check your config files (php.ini and .htaccess), you may have auto_prepend_file set.
check your crontab, [sorry I don't know where you would find it in cpanel]
- does the script fire at a specific time or can you see it definitely fires only when you request a specific page?
-sean
EDIT:
If crontab is out, take a look at index.php [and it's includes] and look for code that either loops over the url parameters without specifically noting "nq" and anything that might be parsing the query string [probably something like: $_SERVER['QUERY_STRING'] ]
-sean
You should give debug_backtrace() (or debug_print_backtrace() a try. The output is similar to the output of an Exception-stacktrace, thus it should help you to find out, what is called when and from where. If you don't have the possibility to run the application on a local development system, make sure, that nobody else can see the output
Are you sure that you are looking at the right config or server? If you go the url above you get an error page that seems to indicate that the server is actually a microsoft iis server and not an apache one.

Categories