Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it a good practice to remove PHP files from the htdocs directory?

Tags:

security

php

Why is it a good practice to remove PHP files from the htdocs/public directory?
They are being parsed anyway, right?

like image 972
Itay Moav -Malimovka Avatar asked Dec 23 '22 07:12

Itay Moav -Malimovka


2 Answers

if PHP files are at some point not parsed due to a configuration error or, say, a failing interpreter, there is no danger of the source code (and possibly passwords) being revealed to the world as clear text.

Also, human mistakes like renaming a .php file to .php.bak are less dangerous that way.

I had this once, years ago, when a colleague, from the Perl world and totally ignorant about PHP, decided to set "short_open_tags" to "off" on a server we shared, because short_open_tags messed with some XML experiment he had going (<?xml version="1.0"?>). That was fun! :)

and a second thing:

Calling includes out of context

Having includes (i.e. pieces of PHP code that is included elsewhere) under the web root makes you potentially vulnerable to people calling those includes directly, out of context, possibly bypassing security checks and initializations.

If you can't/won't avoid PHP code to reside in the web root, at least be sure to start each file checking whether it is running in the correct context.

Set this in your main script(s):

define ("RUNNING_IN_SCRIPT", true);

and add this to the 1st line of each include:

if (!defined("RUNNING_IN_SCRIPT")) die ("This file cannot be called directly.");
like image 92
Pekka Avatar answered Mar 02 '23 18:03

Pekka


Yes, they are parsed. However, that is completely dependent on you or the server admin not screwing up the config files.

All it takes is a quick typo in the Apache config before Apache forgets to parse the PHP (I've had this happen). Since Apache won't know what to do with a PHP file after that, your source code just gets output as plain text, and can be immediately copied. Heck, it's even cached in the user's browser, so a malicious user can quickly copy all your code and browse it later at their convenience, looking for security holes.

You don't want your source to be visible even for a second. If you have no code files in the htdocs directory, this can't happen. They can easily be included into your code from outside the directory however.

Many MVC frameworks use this method of sandboxing for just this purpose.

like image 40
zombat Avatar answered Mar 02 '23 20:03

zombat