Monday, January 11, 2010

Recipe 18.6. Keeping Passwords Out of Your Site Files










Recipe 18.6. Keeping Passwords Out of Your Site Files



18.6.1. Problem


You need

to use a password to connect to a database, for example. You don't want to put the password in the PHP files you use on your site in case those files are exposed.




18.6.2. Solution


Store the password in an environment variable in a file that the web server loads when starting up. Then, just reference the environment variable in your code:


<?php

mysql_connect('localhost', $_SERVER['DB_USER'], $_SERVER['DB_PASSWORD']);

?>





18.6.3. Discussion


While this technique removes passwords from the source code of your pages, it makes them available in other places that need to be protected. Most importantly, make sure that there are no publicly viewable pages that call phpinfo( ). Because
phpinfo( ) displays all of the environment variables, it exposes any passwords you store there. Also, make sure not to expose the contents of $_SERVER
in other ways, such as with the
print_r( ) function.


Next, especially if you are using a shared host, make sure the environment variables are set in such a way that they are only available to your virtual host, not to all users. With Apache, you can do this by setting the variables in a separate file from the main configuration file:


SetEnv  DB_USER     "susannah"
SetEnv DB_PASSWORD "y23a!t@ce8"



Inside the <VirtualHost> directive for the site in the main configuration file (httpd.conf),
include this separate file as follows:


Include "/usr/local/apache/database-passwords"



Make sure that this separate file containing the password (e.g., /usr/local/apache/database-passwords) is not readable by any user other than the one that controls the appropriate virtual host. When Apache starts up and is reading in configuration files, it's usually running as root, so it is able to read the included file. A child process that handles requests typically runs as an unprivileged user, so rogue scripts cannot read the protected file.




18.6.4. See Also


Documentation on Apache's Include directive at http://httpd.apache.org/docs/mod/core.html#include.













No comments: