I was wondering what is the best way to store usernames and password to connect to mysql database?
3 Answers
An easy and safe way — if you do it right — is with a config file. The DBI/DBD MySQL connection string will look something like–
dbi:mysql:my_dbname;mysql_read_default_file=/NON-WEB/path/to/.my.cnf
–and you will pass no user or password to the DBI connection call.
The .my.cnf file will have the password. The ways to keep this safe include–
- File is only readable by the webuser.
- File is outside the web root; visiting a URL cannot possibly reach it.
- The config file contains the bare minimum to connect, it probably does not need the user name for example.
- Make sure there are no exploits in your application that might allow browsing of your file system.
- The webuser's mysql account has limited privileges: no grant, no create|drop tables, etc, etc.
See the chapter Configuring Perl Programs from Mastering Perl.
(Link only due to copy restrictions.)
There is simply no way to safely store the username/password. Because at the end your script always has to be able to get the data, anybody else could possibly go the same way.
If you store the data encrypted, you have to tell your script the key to decrypt. So if somebody reads the script, he get's the key. But in case of an CGI-Environment the script always needs to be readable by the webserver.
If you are not in an CGI-Environment or there is some suExec stuff running, you can get by this limitation by setting the access rights of the script/configfile so that nobody else than the executing user can read the files.
This is safe until some admin comes by and wants to find out whats in there or somebody hacks your account.
-
2The user asked for the "best way" to store this information. And while there are no 100% "safe" ways to store this, some ways are better than others. Keeping this information separate from the code is good practice from a security and maintenance point of view.– RobCommented Feb 19, 2014 at 9:55