[php] How to secure database passwords in PHP?

When a PHP application makes a database connection it of course generally needs to pass a login and password. If I'm using a single, minimum-permission login for my application, then the PHP needs to know that login and password somewhere. What is the best way to secure that password? It seems like just writing it in the PHP code isn't a good idea.

This question is related to php database security

The answer is


We have solved it in this way:

  1. Use memcache on server, with open connection from other password server.
  2. Save to memcache the password (or even all the password.php file encrypted) plus the decrypt key.
  3. The web site, calls the memcache key holding the password file passphrase and decrypt in memory all the passwords.
  4. The password server send a new encrypted password file every 5 minutes.
  5. If you using encrypted password.php on your project, you put an audit, that check if this file was touched externally - or viewed. When this happens, you automatically can clean the memory, as well as close the server for access.

Actually, the best practice is to store your database crendentials in environment variables because :

  • These credentials are dependant to environment, it means that you won't have the same credentials in dev/prod. Storing them in the same file for all environment is a mistake.
  • Credentials are not related to business logic which means login and password have nothing to do in your code.
  • You can set environment variables without creating any business code class file, which means you will never make the mistake of adding the credential files to a commit in Git.
  • Environments variables are superglobales : you can use them everywhere in your code without including any file.

How to use them ?

  • Using the $_ENV array :
    • Setting : $_ENV['MYVAR'] = $myvar
    • Getting : echo $_ENV["MYVAR"]
  • Using the php functions :
  • In vhosts files and .htaccess but it's not recommended since its in another file and its not resolving the problem by doing it this way.

You can easily drop a file such as envvars.php with all environment variables inside and execute it (php envvars.php) and delete it. It's a bit old school, but it still work and you don't have any file with your credentials in the server, and no credentials in your code. Since it's a bit laborious, frameworks do it better.

Example with Symfony (ok its not only PHP) The modern frameworks such as Symfony recommends using environment variables, and store them in a .env not commited file or directly in command lines which means you wether can do :

Documentation :


If you're talking about the database password, as opposed to the password coming from a browser, the standard practice seems to be to put the database password in a PHP config file on the server.

You just need to be sure that the php file containing the password has appropriate permissions on it. I.e. it should be readable only by the web server and by your user account.


Just putting it into a config file somewhere is the way it's usually done. Just make sure you:

  1. disallow database access from any servers outside your network,
  2. take care not to accidentally show the password to users (in an error message, or through PHP files accidentally being served as HTML, etcetera.)

Put the database password in a file, make it read-only to the user serving the files.

Unless you have some means of only allowing the php server process to access the database, this is pretty much all you can do.


If you are using PostgreSQL, then it looks in ~/.pgpass for passwords automatically. See the manual for more information.


Actually, the best practice is to store your database crendentials in environment variables because :

  • These credentials are dependant to environment, it means that you won't have the same credentials in dev/prod. Storing them in the same file for all environment is a mistake.
  • Credentials are not related to business logic which means login and password have nothing to do in your code.
  • You can set environment variables without creating any business code class file, which means you will never make the mistake of adding the credential files to a commit in Git.
  • Environments variables are superglobales : you can use them everywhere in your code without including any file.

How to use them ?

  • Using the $_ENV array :
    • Setting : $_ENV['MYVAR'] = $myvar
    • Getting : echo $_ENV["MYVAR"]
  • Using the php functions :
  • In vhosts files and .htaccess but it's not recommended since its in another file and its not resolving the problem by doing it this way.

You can easily drop a file such as envvars.php with all environment variables inside and execute it (php envvars.php) and delete it. It's a bit old school, but it still work and you don't have any file with your credentials in the server, and no credentials in your code. Since it's a bit laborious, frameworks do it better.

Example with Symfony (ok its not only PHP) The modern frameworks such as Symfony recommends using environment variables, and store them in a .env not commited file or directly in command lines which means you wether can do :

Documentation :


Just putting it into a config file somewhere is the way it's usually done. Just make sure you:

  1. disallow database access from any servers outside your network,
  2. take care not to accidentally show the password to users (in an error message, or through PHP files accidentally being served as HTML, etcetera.)

The most secure way is to not have the information specified in your PHP code at all.

If you're using Apache that means to set the connection details in your httpd.conf or virtual hosts file file. If you do that you can call mysql_connect() with no parameters, which means PHP will never ever output your information.

This is how you specify these values in those files:

php_value mysql.default.user      myusername
php_value mysql.default.password  mypassword
php_value mysql.default.host      server

Then you open your mysql connection like this:

<?php
$db = mysqli_connect();

Or like this:

<?php
$db = mysqli_connect(ini_get("mysql.default.user"),
                     ini_get("mysql.default.password"),
                     ini_get("mysql.default.host"));

Best way is to not store the password at all!
For instance, if you're on a Windows system, and connecting to SQL Server, you can use Integrated Authentication to connect to the database without a password, using the current process's identity.

If you do need to connect with a password, first encrypt it, using strong encryption (e.g. using AES-256, and then protect the encryption key, or using asymmetric encryption and have the OS protect the cert), and then store it in a configuration file (outside of the web directory) with strong ACLs.


The most secure way is to not have the information specified in your PHP code at all.

If you're using Apache that means to set the connection details in your httpd.conf or virtual hosts file file. If you do that you can call mysql_connect() with no parameters, which means PHP will never ever output your information.

This is how you specify these values in those files:

php_value mysql.default.user      myusername
php_value mysql.default.password  mypassword
php_value mysql.default.host      server

Then you open your mysql connection like this:

<?php
$db = mysqli_connect();

Or like this:

<?php
$db = mysqli_connect(ini_get("mysql.default.user"),
                     ini_get("mysql.default.password"),
                     ini_get("mysql.default.host"));

This solution is general, in that it is useful for both open and closed source applications.

  1. Create an OS user for your application. See http://en.wikipedia.org/wiki/Principle_of_least_privilege
  2. Create a (non-session) OS environment variable for that user, with the password
  3. Run the application as that user

Advantages:

  1. You won't check your passwords into source control by accident, because you can't
  2. You won't accidentally screw up file permissions. Well, you might, but it won't affect this.
  3. Can only be read by root or that user. Root can read all your files and encryption keys anyways.
  4. If you use encryption, how are you storing the key securely?
  5. Works x-platform
  6. Be sure to not pass the envvar to untrusted child processes

This method is suggested by Heroku, who are very successful.


If you're talking about the database password, as opposed to the password coming from a browser, the standard practice seems to be to put the database password in a PHP config file on the server.

You just need to be sure that the php file containing the password has appropriate permissions on it. I.e. it should be readable only by the web server and by your user account.


Put the database password in a file, make it read-only to the user serving the files.

Unless you have some means of only allowing the php server process to access the database, this is pretty much all you can do.


Just putting it into a config file somewhere is the way it's usually done. Just make sure you:

  1. disallow database access from any servers outside your network,
  2. take care not to accidentally show the password to users (in an error message, or through PHP files accidentally being served as HTML, etcetera.)

if it is possible to create the database connection in the same file where the credentials are stored. Inline the credentials in the connect statement.

mysql_connect("localhost", "me", "mypass");

Otherwise it is best to unset the credentials after the connect statement, because credentials that are not in memory, can't be read from memory ;)

include("/outside-webroot/db_settings.php");  
mysql_connect("localhost", $db_user, $db_pass);  
unset ($db_user, $db_pass);  

We have solved it in this way:

  1. Use memcache on server, with open connection from other password server.
  2. Save to memcache the password (or even all the password.php file encrypted) plus the decrypt key.
  3. The web site, calls the memcache key holding the password file passphrase and decrypt in memory all the passwords.
  4. The password server send a new encrypted password file every 5 minutes.
  5. If you using encrypted password.php on your project, you put an audit, that check if this file was touched externally - or viewed. When this happens, you automatically can clean the memory, as well as close the server for access.

Store them in a file outside web root.


An additional trick is to use a PHP separate configuration file that looks like that :

<?php exit() ?>

[...]

Plain text data including password

This does not prevent you from setting access rules properly. But in the case your web site is hacked, a "require" or an "include" will just exit the script at the first line so it's even harder to get the data.

Nevertheless, do not ever let configuration files in a directory that can be accessed through the web. You should have a "Web" folder containing your controler code, css, pictures and js. That's all. Anything else goes in offline folders.


Best way is to not store the password at all!
For instance, if you're on a Windows system, and connecting to SQL Server, you can use Integrated Authentication to connect to the database without a password, using the current process's identity.

If you do need to connect with a password, first encrypt it, using strong encryption (e.g. using AES-256, and then protect the encryption key, or using asymmetric encryption and have the OS protect the cert), and then store it in a configuration file (outside of the web directory) with strong ACLs.


Store them in a file outside web root.


If you're hosting on someone else's server and don't have access outside your webroot, you can always put your password and/or database connection in a file and then lock the file using a .htaccess:

<files mypasswdfile>
order allow,deny
deny from all
</files>

if it is possible to create the database connection in the same file where the credentials are stored. Inline the credentials in the connect statement.

mysql_connect("localhost", "me", "mypass");

Otherwise it is best to unset the credentials after the connect statement, because credentials that are not in memory, can't be read from memory ;)

include("/outside-webroot/db_settings.php");  
mysql_connect("localhost", $db_user, $db_pass);  
unset ($db_user, $db_pass);  

Your choices are kind of limited as as you say you need the password to access the database. One general approach is to store the username and password in a seperate configuration file rather than the main script. Then be sure to store that outside the main web tree. That was if there is a web configuration problem that leaves your php files being simply displayed as text rather than being executed you haven't exposed the password.

Other than that you are on the right lines with minimal access for the account being used. Add to that

  • Don't use the combination of username/password for anything else
  • Configure the database server to only accept connections from the web host for that user (localhost is even better if the DB is on the same machine) That way even if the credentials are exposed they are no use to anyone unless they have other access to the machine.
  • Obfuscate the password (even ROT13 will do) it won't put up much defense if some does get access to the file, but at least it will prevent casual viewing of it.

Peter


If you are using PostgreSQL, then it looks in ~/.pgpass for passwords automatically. See the manual for more information.


Previously we stored DB user/pass in a configuration file, but have since hit paranoid mode -- adopting a policy of Defence in Depth.

If your application is compromised, the user will have read access to your configuration file and so there is potential for a cracker to read this information. Configuration files can also get caught up in version control, or copied around servers.

We have switched to storing user/pass in environment variables set in the Apache VirtualHost. This configuration is only readable by root -- hopefully your Apache user is not running as root.

The con with this is that now the password is in a Global PHP variable.

To mitigate this risk we have the following precautions:

  • The password is encrypted. We extend the PDO class to include logic for decrypting the password. If someone reads the code where we establish a connection, it won't be obvious that the connection is being established with an encrypted password and not the password itself.
  • The encrypted password is moved from the global variables into a private variable The application does this immediately to reduce the window that the value is available in the global space.
  • phpinfo() is disabled. PHPInfo is an easy target to get an overview of everything, including environment variables.

If you are using PostgreSQL, then it looks in ~/.pgpass for passwords automatically. See the manual for more information.


Store them in a file outside web root.


Previously we stored DB user/pass in a configuration file, but have since hit paranoid mode -- adopting a policy of Defence in Depth.

If your application is compromised, the user will have read access to your configuration file and so there is potential for a cracker to read this information. Configuration files can also get caught up in version control, or copied around servers.

We have switched to storing user/pass in environment variables set in the Apache VirtualHost. This configuration is only readable by root -- hopefully your Apache user is not running as root.

The con with this is that now the password is in a Global PHP variable.

To mitigate this risk we have the following precautions:

  • The password is encrypted. We extend the PDO class to include logic for decrypting the password. If someone reads the code where we establish a connection, it won't be obvious that the connection is being established with an encrypted password and not the password itself.
  • The encrypted password is moved from the global variables into a private variable The application does this immediately to reduce the window that the value is available in the global space.
  • phpinfo() is disabled. PHPInfo is an easy target to get an overview of everything, including environment variables.

If you're talking about the database password, as opposed to the password coming from a browser, the standard practice seems to be to put the database password in a PHP config file on the server.

You just need to be sure that the php file containing the password has appropriate permissions on it. I.e. it should be readable only by the web server and by your user account.


For extremely secure systems we encrypt the database password in a configuration file (which itself is secured by the system administrator). On application/server startup the application then prompts the system administrator for the decryption key. The database password is then read from the config file, decrypted, and stored in memory for future use. Still not 100% secure since it is stored in memory decrypted, but you have to call it 'secure enough' at some point!


Your choices are kind of limited as as you say you need the password to access the database. One general approach is to store the username and password in a seperate configuration file rather than the main script. Then be sure to store that outside the main web tree. That was if there is a web configuration problem that leaves your php files being simply displayed as text rather than being executed you haven't exposed the password.

Other than that you are on the right lines with minimal access for the account being used. Add to that

  • Don't use the combination of username/password for anything else
  • Configure the database server to only accept connections from the web host for that user (localhost is even better if the DB is on the same machine) That way even if the credentials are exposed they are no use to anyone unless they have other access to the machine.
  • Obfuscate the password (even ROT13 will do) it won't put up much defense if some does get access to the file, but at least it will prevent casual viewing of it.

Peter


An additional trick is to use a PHP separate configuration file that looks like that :

<?php exit() ?>

[...]

Plain text data including password

This does not prevent you from setting access rules properly. But in the case your web site is hacked, a "require" or an "include" will just exit the script at the first line so it's even harder to get the data.

Nevertheless, do not ever let configuration files in a directory that can be accessed through the web. You should have a "Web" folder containing your controler code, css, pictures and js. That's all. Anything else goes in offline folders.


For extremely secure systems we encrypt the database password in a configuration file (which itself is secured by the system administrator). On application/server startup the application then prompts the system administrator for the decryption key. The database password is then read from the config file, decrypted, and stored in memory for future use. Still not 100% secure since it is stored in memory decrypted, but you have to call it 'secure enough' at some point!


Put the database password in a file, make it read-only to the user serving the files.

Unless you have some means of only allowing the php server process to access the database, this is pretty much all you can do.


This solution is general, in that it is useful for both open and closed source applications.

  1. Create an OS user for your application. See http://en.wikipedia.org/wiki/Principle_of_least_privilege
  2. Create a (non-session) OS environment variable for that user, with the password
  3. Run the application as that user

Advantages:

  1. You won't check your passwords into source control by accident, because you can't
  2. You won't accidentally screw up file permissions. Well, you might, but it won't affect this.
  3. Can only be read by root or that user. Root can read all your files and encryption keys anyways.
  4. If you use encryption, how are you storing the key securely?
  5. Works x-platform
  6. Be sure to not pass the envvar to untrusted child processes

This method is suggested by Heroku, who are very successful.


Store them in a file outside web root.


If you are using PostgreSQL, then it looks in ~/.pgpass for passwords automatically. See the manual for more information.


Your choices are kind of limited as as you say you need the password to access the database. One general approach is to store the username and password in a seperate configuration file rather than the main script. Then be sure to store that outside the main web tree. That was if there is a web configuration problem that leaves your php files being simply displayed as text rather than being executed you haven't exposed the password.

Other than that you are on the right lines with minimal access for the account being used. Add to that

  • Don't use the combination of username/password for anything else
  • Configure the database server to only accept connections from the web host for that user (localhost is even better if the DB is on the same machine) That way even if the credentials are exposed they are no use to anyone unless they have other access to the machine.
  • Obfuscate the password (even ROT13 will do) it won't put up much defense if some does get access to the file, but at least it will prevent casual viewing of it.

Peter


If you're talking about the database password, as opposed to the password coming from a browser, the standard practice seems to be to put the database password in a PHP config file on the server.

You just need to be sure that the php file containing the password has appropriate permissions on it. I.e. it should be readable only by the web server and by your user account.


If you're hosting on someone else's server and don't have access outside your webroot, you can always put your password and/or database connection in a file and then lock the file using a .htaccess:

<files mypasswdfile>
order allow,deny
deny from all
</files>

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to database

Implement specialization in ER diagram phpMyAdmin - Error > Incorrect format parameter? Authentication plugin 'caching_sha2_password' cannot be loaded Room - Schema export directory is not provided to the annotation processor so we cannot export the schema SQL Query Where Date = Today Minus 7 Days MySQL Error: : 'Access denied for user 'root'@'localhost' SQL Server date format yyyymmdd How to create a foreign key in phpmyadmin WooCommerce: Finding the products in database TypeError: tuple indices must be integers, not str

Examples related to security

Monitoring the Full Disclosure mailinglist Two Page Login with Spring Security 3.2.x How to prevent a browser from storing passwords JWT authentication for ASP.NET Web API How to use a client certificate to authenticate and authorize in a Web API Disable-web-security in Chrome 48+ When you use 'badidea' or 'thisisunsafe' to bypass a Chrome certificate/HSTS error, does it only apply for the current site? How does Content Security Policy (CSP) work? How to prevent Screen Capture in Android Default SecurityProtocol in .NET 4.5