Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safe approach of storing MySQL credentials [duplicate]

I've just started studying PHP and having concluded my first PHP & MySQL for dummies book I have a concern about having a secure connection between my PHP application and MySQL database.

From what I learned, one approach is to create a .php file with the database credentials, for example:

--- database.php ---

<?php

define('HOST', 'localhost');
define('DB_USR' , 'mysql_username');
define('DB_PSWD' , 'mysql_password');
define('DB_NAME' , 'mysql_newbie');

?>

and then place a require_once('database.php') in every PHP page that requires any sort of database queries.

My concern is whether this approach is safe. Isn't the file database.php accessible to everyone once it's placed on the webserver?
Anyone can potentially read the database's credentials and mess his way around it?

Any thoughts?

like image 276
Filippos Avatar asked Oct 22 '25 04:10

Filippos


1 Answers

The first things you have to look at are the different attack vectors.

One vector is remote users coming via HTTP, the other main vector is local users with shell access or similar on the machine.

Protecting against the first one is relatively easy: Make sure the content is not shared via HTTP. A simple way is to call the file .php so that when a user guesses the name the PHP script is executed and produces no output (that's what you already did) Slightly better is to prevent access to the file from the server config. Both of those approaches still depend on your operations, to make sure you don't break the config by accident. Better is to move the file outside the web root, into a completely different directory. Files outside the document root can't be accessed via the server and thus never leak.

For preventing local attacks the protection is to restrict access rights to the web server (i.e. make it owned by the web server and giving reading permissions only to that user account), this however still leaves a vector open for an attacker who can install scripts in a different vhost of the server (if it is a shard server) the mitigation there might be PHP's "open_basedir" setting, where PHP prevents access to files in a different directory. This has to be configured per vhost in the server's config.

like image 150
johannes Avatar answered Oct 23 '25 17:10

johannes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!