How to secure database passwords in PHP?

229,864

Solution 1

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.

Solution 2

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>

Solution 3

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

Solution 4

Store them in a file outside web root.

Solution 5

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!

Share:
229,864
user18359
Author by

user18359

Updated on December 29, 2020

Comments

  • user18359
    user18359 over 3 years

    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.

  • user18359
    user18359 almost 16 years
    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!
  • Matthew Rapati
    Matthew Rapati almost 16 years
    yep, I usually do DEFINE("DB_NAME","mydb"); etc it is also handy to define anything you'll be using on more then page, that you might want to change later
  • AviD
    AviD almost 16 years
    Just saving the password in a config file is not much more secure. It needs to be properly protected, using strong ACLs and strong encryption with properly protected keys... See my post below.
  • user11318
    user11318 almost 16 years
    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?
  • Lucas Meijer
    Lucas Meijer over 15 years
    but then how does the php script read the credentials stored in the file?
  • e-satis
    e-satis over 15 years
    You use fopen(), like for a regular text file.
  • gnud
    gnud about 15 years
    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.
  • AviD
    AviD about 15 years
    @bentilly, that's where strong Key Management comes in, and this should definitely be the developer's responsibility, not the admin's - though the admins also have some tasks here too.
  • Frank Farmer
    Frank Farmer about 15 years
    And also, as mentioned elsewhere, outside of source control.
  • Kzqai
    Kzqai about 14 years
    Useful, if it's truly secure, though it seems like a shell login would still have access.
  • kellen
    kellen about 14 years
    Definitely, but if someone has shell access, your entire account has been compromised anyway.
  • atamanroman
    atamanroman almost 14 years
    @bentilly so when you dont expose sensitive data theres no need for encryption at all? Not encrypting because you dont think anyone unprivileged would get access sounds odd for me - it makes the PIN on my VISA useless, since nobody should get access to it. edit: sorry, someone dug out an old thread
  • Val
    Val about 12 years
    Please check the proper values of ini_get('default values') php.net/manual/en/class.mysqli.php
  • Admin
    Admin almost 12 years
    Could one use this in their .htaccess file?
  • C graphics
    C graphics almost 12 years
    @gnut: " I just store it outside the web root. ". How string it outside webroot would help? I am asking this as I have seen in even modern open source scripts that the config file which contains the db password is in root. I dont prefer this and I wanna know if I sould bother.
  • uliwitness
    uliwitness almost 12 years
    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
    uliwitness almost 12 years
    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.
  • AviD
    AviD almost 12 years
    @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.
  • mtk
    mtk over 11 years
    we would be able to include it? e.g. in PHP can we then do include('../otherDirectory/configfile.conf') ?
  • dmnc
    dmnc over 10 years
    @MatthewRapati ... I'm actually solving problem with password in constants, because other developers can simple do get_defined_constants().
  • dmnc
    dmnc over 10 years
    @e-satis ok it will prevent hacker to do require/include but how to prevent to do fopen?
  • e-satis
    e-satis over 10 years
    "this does not prevent you from setting access rules properly"
  • geedew
    geedew over 10 years
    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
  • MarioVilas
    MarioVilas about 10 years
    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
    MarioVilas about 10 years
    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.
  • AviD
    AviD about 10 years
    @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.
  • MarioVilas
    MarioVilas almost 10 years
    @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.
  • Rick Mac Gillis
    Rick Mac Gillis over 9 years
    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.
  • ILikeTacos
    ILikeTacos over 9 years
    @RaduMurzea that's ridiculous. When have you heard of Sys Admins dying? They're like McDonalds, they just appear/disappear out of nowhere!
  • element11
    element11 almost 9 years
    @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.
  • John Hunt
    John Hunt over 8 years
    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
  • Ankit
    Ankit over 8 years
    For all the people who are asking how to protect from all other than me, the answer is either manage the whole company by yourself, otherwise you have to trust at least someone.
  • Ankit
    Ankit over 8 years
    @henk There is no solution for this. You have to trust or be careful about the contents of all the scripts that are going to the production server.
  • Ankit
    Ankit over 8 years
    There is no real solution for this. Anyone can use dump functions in file, upload the file to production server and execute it. Yayy you got all the secrets of production server !
  • Marki555
    Marki555 over 8 years
    yes, but any user (or a hacker abusing badly written php script) can read the password via ini_get().
  • tonix
    tonix about 8 years
    @RickMacGillis If someone includes that file, then dumps the data from the file, they will see the password how do you deal with this?
  • tonix
    tonix about 8 years
    @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?
  • Lars Nyström
    Lars Nyström about 8 years
    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().
  • Marki555
    Marki555 about 8 years
    @tonix as already written, if "good" script has access to db password, then also "bad" script does. So your only option is to detect such scripts and don't allow them to run, for example using mod_security apache module, although it is not trivial to fine-tune the rules correctly.
  • tonix
    tonix about 8 years
    @Marki555 I can think of using a single DB connection entry point where I read the password and the username of the database and pass them to the connection engine in order to get the database connection and then unset those variables. At this point I need to beware everyone's push to the codebase and assure that there are no changes to that entry point file and no one is trying to dump the password of the database somehow. Could it be enough?
  • Rick Mac Gillis
    Rick Mac Gillis about 8 years
    @tonix The issue is more of an issue with open source software, as you'll have knowledge of the variables or layout of that file. For that reason, define is a bad idea for setting those variables. (Ex. WordPress uses that insecure method and it has it inside of the web-accessible directory.) The issue I was pointing out is that if someone is able to upload a file, they can discover the passwords in that file. However, even though someone can easily dump the password created with define, Laravel's .env or array-based config files are only mildly better. Every file is susceptible to attack.
  • Rick Mac Gillis
    Rick Mac Gillis about 8 years
    To avoid this issue in the first place, use a password server and query the server for the information you need. AWS KMS could be used to help secure your passwords further by keeping them encrypted in the file-system, and only decrypt them in memory with Redis. aws.amazon.com/kms
  • Rick Mac Gillis
    Rick Mac Gillis about 8 years
    Then again, if someone can place a file on your site and run it, you have bigger issues than just losing your passwords. That file can do anything.
  • Porlune
    Porlune about 8 years
    This is bad practice because you might accidentally commit your credentials to a repository.
  • kellen
    kellen about 8 years
    @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.
  • kellen
    kellen about 8 years
    @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.
  • nurulhudamustaqim
    nurulhudamustaqim almost 8 years
    iam 100% agreed, that was oracle weblogic done with boot.properties
  • Luke A. Leber
    Luke A. Leber over 7 years
    @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.
  • DeepBlue
    DeepBlue over 7 years
    Having the pass in config file outside root, is safer that exposing it to ini_get() or getenv() that could be injected and executed from anywhere in the website.
  • varesa
    varesa about 7 years
    @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.
  • Mohammed Joraid
    Mohammed Joraid about 7 years
    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.
  • bdsl
    bdsl almost 7 years
    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.
  • Chris Seufert
    Chris Seufert over 6 years
    I think this is a very bad idea, if the server has a phpinfo() floating around, this will leak your password.
  • user1119648
    user1119648 over 6 years
    @bdsl Redis or Memcache
  • The Godfather
    The Godfather almost 6 years
    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"?
  • David
    David almost 6 years
    @element11 Just be sure they never drive to McDonald's for lunch together in the same car!
  • PhoneixS
    PhoneixS over 4 years
    @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).
  • Pacerier
    Pacerier about 4 years
    @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
  • Robert Talada
    Robert Talada about 4 years
    Except administrators almost never secure them because they usually aren't even aware they are there. lol.
  • Robert Talada
    Robert Talada about 4 years
    @Porlune Ok, but you might also accidentally type the password into a user field and have it stored in a plaintext log file. At some point, people have to be expected to do their job correctly. You cannot eliminate every risk. It's a fallacy that you can make any entirely system safe from error.
  • Porlune
    Porlune about 4 years
    @RobertTalada W/r/t this particular solution, it's important that those with a limited background in security practices are given a heads up of potential pitfalls. User fields in a browser are out of scope, but repository commits are not.
  • Robert Talada
    Robert Talada almost 4 years
    @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.
  • MrWhite
    MrWhite over 3 years
    "This configuration is only readable by root" - although the environment variables that are set are presumably readable by everyone?
  • MrWhite
    MrWhite over 3 years
    @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()".
  • Courtney Miles
    Courtney Miles over 3 years
    @MrWhite, the env variable would only be set for user Apache runs as. So it is definitely not readable for everyone.
  • MarioVilas
    MarioVilas over 3 years
    @MrWhite you are absolutely right of course. I misunderstood the answer to mean storing the database credentials in php.ini itself.