Saturday, 21 May 2011

Improve PHP Security – Part II. Restrict open_basedir

By default, PHP allows it’s files to have access to all your server. Everything. It is a miracle that people didn’t take advantage of that and destroyed most of the web :)

Restricting is good but remember there are some directories that PHP should have access so we will not restrict everything.

Restrict open_basedir
I chose to give PHP access to /home/www (where I intend to store my websites) and what it already needed. You could allow more directories. When (if) you will install the Zend Framework you will have to add that to the list of directories.
vi /etc/php.ini
Add open_basedir /home/www:/usr/lib/php:/usr/local/lib/php:/tmp
Add (modify) disable_functions = symlink


Restart Apache HTTPD
service httpd restart

Test open_basedir
It might be a little harder to test before you create Virtual Hosts, have a DNS server and at least 2 different websites on your server. You might want to do that again.
You could still test it from your default web directory (I will assume that is /var/www/html).

Create the test files
You will create to txt files. The first will be placed in / (root) where PHP should not have access and one will be placed in the local directory of your web site.

cd /
vi testBaseDir.txt

Add something like:
I should not see this!
(then press Esc, :wq, Enter)

cd /var/www/html
vi testBaseDir.txt

Use your creativity to write a better line:
To be, or not be safe!
Please learn vi! I promise to add a post on that soon.

vi testReadLocal.php
And add this code:
<?php
$myFile = "testBaseDir.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, filesize($myFile));
fclose($fh);
echo $theData;
?>


vi testReadRoot.php
And add this code:
<?php
$myFile = "/testBaseDir.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, filesize($myFile));
fclose($fh);
echo $theData;
?>


Run the test
Use lynx or your browser (if iptables will let you) and access testReadRoot.php and testReadLocal.php.
The first should not work while the second should.

No comments:

Post a Comment