ChatGPT解决这个技术问题 Extra ChatGPT

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.

To be totally secure, you'll need to set up an ssl connection, otherwise anyone on your network can still sniff the password you type.
Do you mean the user passwords or the database password used in the connection string?
Database password used in the connection string. Thanks!

F
Farray

Several people misread this as a question about how to store passwords in a database. That is wrong. It is about how to store the password that lets you get to the database.

The usual solution is to move the password out of source-code into a configuration file. Then leave administration and securing that configuration file up to your system administrators. That way developers do not need to know anything about the production passwords, and there is no record of the password in your source-control.


Thanks. If I understand this correctly, the php file will then have an include to the config file, allowing it to use the password. e.g. I create a file called 'app1_db_cfg.php' that stores the login, pword, & db name. Then my application.php page includes 'app1_db_cfg.php' and I'm in business!
I agree that the config needs to be properly protected. However knowing how to do that is the business of system administrators, not developers. I disagree on the value of strong encryption in this case. If you can't protect your config file, what makes you think you can protect your keys?
I prefer using a database account that is only allowed to acces the database from the web server. And then I don't bother encrypting the configuration, I just store it outside the web root.
I use an apache environment variable to set the path so that even the path to the file is unknown in the source code. This also nicely allows having a different password for development and production based on what Apache settings are on the serverm
Please keep in mind that even files stored outside of the web accessible directory must be read by the script that uses them. If someone includes that file, then dumps the data from the file, they will see the password.
k
kellen

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>

Thanks, that was exactly what I was looking for.
Definitely, but if someone has shell access, your entire account has been compromised anyway.
This is bad practice because you might accidentally commit your credentials to a repository.
@Ankit: If it's possible for a non-friendly to upload a file to the server and execute it, then the server is not properly configured.
@Porlune: Developers should make their version control system ignore the password file, i.e. by using a .gitignore. But yes, care should be taken with files that contain sensitive data.
F
Funk Forty Niner

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"));

Please check the proper values of ini_get('default values') php.net/manual/en/class.mysqli.php
yes, but any user (or a hacker abusing badly written php script) can read the password via ini_get().
@Marki555 but any user (or a hacker abusing badly written php script) can read the password via ini_get() How do you deal with this?
Marki555 is saying that an attacker who can run PHP code can also call PHP functions, which is obviously true and impossible to do something about. I would also like to add that I no longer follow the advice I give in this answer myself, but instead use environment variables. The concept is similar though: Don't store your credentials in the code, but inject them somehow. It doesn't really matter if you use ini_get() or getenv().
@DeepBlue If you can inject ini_get() you can inject file_get_contents(anypath) as well. As long as php has a way to get to the password, so will any malicious code.
d
da5id

Store them in a file outside web root.


And also, as mentioned elsewhere, outside of source control.
we would be able to include it? e.g. in PHP can we then do include('../otherDirectory/configfile.conf') ?
You're all suggesting to store credentials outside wwwroot. Ok, I understand the security background. But how should it be stored in version control then (sample config)? Usually wwwroot is the root of git repo, so if there is anything outside - it will be outside of VC. Imagine new developer trying to set up a local instance for development - how should he know magic like "take this file, copy it outside and fill in"?
@TheGodfather The idea is that a new developer should have their own credentials for their own development environment. Although is a good practice to have a readme with instructions or comments in the code indicating how you should configure it (but not the actual data).
p
pdavis

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!


@RaduMurzea that's ridiculous. When have you heard of Sys Admins dying? They're like McDonalds, they just appear/disappear out of nowhere!
@Radu Murzea Just have 2 or more admins, then you have parity like a raid array. Chances of more than one drive failing at a time is much lower.
what about when the servers restart? What about the time it takes to wake the admin up to get them to type the password in..etc.etc. lol
iam 100% agreed, that was oracle weblogic done with boot.properties
Not sure what you mean by 'stored in memory'. PHP web apps don't generally store anything in memory for longer than the time it takes to respond to an individual request to see a page.
N
Neil McGuigan

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

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

Advantages:

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

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


B
Bob Fanger

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);  

If someone has access to the memory, you're screwed anyway. This is pointless fake-security. Outside the webroot (or at the least protected by a .htaccess if you don't have access above your webroot) is the only safe option.
@uliwitness - That's like saying that just because someone can cut through your network operation center's lock with an acetylene torch means that the door is also fake security. Keeping sensitive information bound to the tightest possible scope always makes sense.
How about echo $db_user or printing the $db_pass ? Even developers on the same team should not be able to figure out the production credentials. The code should contain nothing printable about the login info.
@LukeA.Leber With proper security in place, the lock should add no further security. The lock is only there to make it less likely equipment will get stolen but just in case the equipment is stolen, the equipment should contain no sensitive and/or unencrypted data.
C
Courtney Miles

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.


"This configuration is only readable by root" - although the environment variables that are set are presumably readable by everyone?
@MrWhite, the env variable would only be set for user Apache runs as. So it is definitely not readable for everyone.
J
Jim

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


V
Vagnerr

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


A
Asi Azulay

We have solved it in this way:

Use memcache on server, with open connection from other password server. Save to memcache the password (or even all the password.php file encrypted) plus the decrypt key. The web site, calls the memcache key holding the password file passphrase and decrypt in memory all the passwords. The password server send a new encrypted password file every 5 minutes. 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.


C
Chris

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.


J
Jason Wadsworth

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.


Unfortunately the PHP config file can be read by phpinfo() and if someone happens to leave some test script behind a lucky attacker would be able to read the password. It's probably best to leave the connection password in a file outside the web server root instead. Then the only way to access it is either with a shell or by executing arbitrary code, but in that scenario all security is lost anyway.
@MarioVilas "the PHP config file can be read by phpinfo()" - I think the answer is referring to an arbitrary PHP script that contains the config information, not the php.ini (config) file (which I assume is what you're referring to). This won't be "readable by phpinfo()".
@MrWhite you are absolutely right of course. I misunderstood the answer to mean storing the database credentials in php.ini itself.
e
e-satis

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.


but then how does the php script read the credentials stored in the file?
You use fopen(), like for a regular text file.
@e-satis ok it will prevent hacker to do require/include but how to prevent to do fopen?
"this does not prevent you from setting access rules properly"
@e-satis, this is pretty clever. wonder why no one had thought of it. However, still vulnerable to the editor copy problem. feross.org/cmsploit
R
Raptor

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

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


A
AviD

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.


No point in encrypting the password again. Someone who could get at the unencrypted password can also get at whatever passphrase is needed to decrypt the password. However, using ACLs & .htaccess is a good idea.
@uliwitness I think you may have misunderstood - what do you mean by "encrypt again"? It's just the one encryption. And you don't want to be using passphrases (intended for human use) to encrypt it, rather strong key management, e.g. protected by the OS, in such a way that simply accessing the file system will not grant access to the key.
Encryption is not magic - instead of protecting the AES key with ACLs you could just store the password there. There is no difference between accessing the AES key or the decrypted password, encryption in this context is just snake oil.
@MarioVilas whaat? If the password is encrypted, with the encryption key protected by the OS, how is there no difference? Encryption is not magic - it just compacts all the secrecy into the smaller encryption key. Hardly snakeoil, in this context it is just moving all that secrecy into the OS.
@AviD how come the OS can protect the key but not the data itself? Answer: it can protect both, so encryption doesn't really help. It'd be different if only the data was stored and the encryption key was derived, for example, from a password that had to be typed by a user.
B
Bruno Guignard

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"]

Setting : $_ENV['MYVAR'] = $myvar

Getting : echo $_ENV["MYVAR"]

Using the php functions : Setting with the putenv function - putenv("MYVAR=$myvar"); Getting with the getenv function - getenv('MYVAR');

Setting with the putenv function - putenv("MYVAR=$myvar");

Getting with the getenv function - getenv('MYVAR');

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 :

With CLI : symfony var:set FOO=bar --env-level

With .env or .env.local : FOO="bar"

Documentation :


关注公众号,不定期副业成功案例分享
Follow WeChat

Success story sharing

Want to stay one step ahead of the latest teleworks?

Subscribe Now