PHP odd variable Question. Pertaining to "Root" - php

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

Related

Deny access to public php from browser but allow application use

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"

make folder secure in php

I am interested to know what is considered more secure out of
include $_SERVER['DOCUMENT_ROOT'] . '/config/special.php';
and
include '../config/special.php';
I see a lot of answers on Stack Overflow and elsewhere on the web that say to store data outside the document root. I have also seen a lot of tutorials that say to include a file in php do something like
include $_SERVER['DOCUMENT_ROOT'] . '/config/special.php';
Would it be ok to do the above if you change the permissions on the folder to something like drwxr-x-wx so you get forbidden if you are trying to access the path in the url (or is this still considered a risk) or would it be better to move my config above my root folder like the below.
include '../config/special.php';
The answer is: "how secure is the rest of your server"?
If you forbid access to the directory from Apache remote calls, you've solved half of the issue regardless of where you store your files. However, this isn't the silver bullet of security. If it was, people would know about it! (I proved this where I work a month ago - one of the lead devs thought that storing stuff in a non-webroot subfolder would make everything secure. Little did he know about the file explorer that he built, and more importantly, how it could take ../ as a parameter and work accordingly... 30s later, database got dumped - on a dev environment).
The key to security is to harden everything. If you allow users to read files, make sure to ban the .. and ... operators, and anything related to it, to prevent them from traversing up the directory chain. Prevent outside users from reading the file (.htaccess with Apache), and that should deter most people.
Depending on how you sanitize the up-one and up-two chains, however, you might end up with more issues. Take the example of my co-worker again: after the dump, he decided to operate these replacements:
.. => .
... => .
(Order is important)
Little did he know about me putting in .... . First regexp would turn this into .., second regexp would do nothing. Bingo, database got dumped. Again.
On a broader more succinct note if you are looking for a straight forward answer to your PHP question.
None of the above are or are not secure. Simply including a file is a normal and warranted action in any PHP application and security would not be effected by any of the above methods.
If you want to read more about security I suggest reading more about how to ensure your server / application is secure.
Perhaps this could be a nice read.
http://www.ibm.com/developerworks/opensource/library/os-php-secure-apps/index.html

PHP / xdebug profiler require_once poor performance

I just started using xdebug to profile my application and immediately noticed something strange in the results. One of the require_once functions is shown to be taking around 12% of the processing time. There are quite a few other calls to require_once throughout the application and they're all taking less than 1% of the processing time.
The poorly-performing require_once is including a file that's not significantly different or larger than any of the other files, so I'm not sure what could be causing the problem. Has anybody else ever experienced something like this?
Edit: Wanted to provide a little more info. I'm doing the profiling on windows using XAMPP. Normally the application runs on a unix box. I haven't got an easy way to get xdebug onto the box, so it may not be feasible for me to try and compare the results that way.
One last edit: Here's an idea of the code in case that helps (intentionally being vague for the standard CYA legal reasons blah blah blah):
This class is the one with the slow include (test.inc):
require_once('/xx/yy/zz/dao/basedao.inc');
require_once('/xx/yy/zz/vo/test.inc');
class TestDAO extends BaseDAO {
// bunch of code to handle database records and return VO objects
And this is the file being included:
require_once('/xx/yy/zz/vo/basevo.inc');
class Test extends BaseVO {
// bunch of properties, getters/setters, that kinda stuff
I have quite a few other VO/DAO objects that are built the exact same way, without any issue. All are located within the same respective paths.
That does indeed sound odd. Definitely worth pursuing, though it'll be hard to work it out for sure without seeing the actual code. 12% of the total program time for a single require_once() does sound very excessive.
But here are some thoughts on possible avenues of investigation:
require_once() keeps a lookup table of files that have been included, so perhaps it's slowing things down having to refer to that lookup table.
If this is the cause, you could solve it by using require() rather than require_once() wherever possible.
Perhaps it's the path lookup? Are you including a path with the filename? If not, it'll be checking in a number of places to find the file; perhaps it isn't in the first place it looks, it'll be taking longer to find the file before it can include it.
If this is the cause, you could solve it by being more specific about the path in your code.
Hope that helps. Would be interested to hear how this pans out.
Oh, and by the way -- if your biggest problem area in your code is require_once(), then it sounds like you've done a good job with your code! I dream of the day require_once() even shows up in my profiler reports, let alone with an significant effect.

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.

How do I execute PHP that is stored in a MySQL database?

I'm trying to write a page that calls PHP that's stored in a MySQL database. The page that is stored in the MySQL database contains PHP (and HTML) code which I want to run on page load.
How could I go about doing this?
You can use the eval command for this. I would recommend against this though, because there's a lot of pitfalls using this approach. Debugging is hard(er), it implies some security risks (bad content in the DB gets executed, uh oh).
See When is eval evil in php? for instance. Google for Eval is Evil, and you'll find a lot of examples why you should find another solution.
Addition: Another good article with some references to exploits is this blogpost. Refers to past vBulletin and phpMyAdmin exploits which were caused by improper Eval usage.
Easy:
$x // your variable with the data from the DB
<?php echo eval("?>".$x."<?") ?>
Let me know, works great for me in MANY applications, can't help but notice that everyone is quick to say how bad it is, but slow to actually help out with a straight answer...
eval() function was covered in other responses here. I agree you should limit use of eval unless it is absolutely needed. Instead of having PHP code in db you could have just a class name that has method called, say, execute(). Whenever you need to run your custom PHP code just instantiate the class of name you just fetched from db and run ->execute() on it. It is much cleaner solution and gives you great field of flexibility and improves site security significantly.
You can look at the eval function in PHP. It allows you to run arbitrary PHP code. It can be a huge security risk, though, and is best avoided.
Have you considered using your Source Control system to store different forks for the various installations (and the modules that differ among them)? That would be one of several best practices for application configuration I can think of. Yours is not an unusual requirement, so it's a problem that's been solved by others in the past; and storing code in a database is one I think you'd have a hard time finding reference to, or being advised as a best practice.
Good thing you posted the clarification. You've probably unintentionally posed an answer in search of a suitable question.
Read php code from database and save to file with unique name and then include file
this easy way for run php code and debug it.
$uniqid="tmp/".date("d-m-Y h-i-s").'_'.$Title."_".uniqid().".php";
$file = fopen($uniqid,"w");
fwrite($file,"<?php \r\n ".$R['Body']);
fclose($file);
// eval($R['Body']);
include $uniqid;
How I did this is to have a field in the database that identified something unique about the block of code needing to be executed. That one word is in the file name of that code. I put the strings together to point to the php file to be included. example:
$lookFor = $row['page'];
include("resources/" . $lookFor . "Codebase.php");
In this way even if a hacker could access you DB he couldn't put malicious code straight in there to be executed. He could perhaps change the reference word, but unless he could actually put a file directly onto the server it would do him no good. If he could put files directly onto the server, you're sunk then anyway if he really wants to be nasty. Just my two cents worth.
And yes, there are reasons you would want to execute stored code, but there are cons.

Categories