Currently in PHP (in the file /var/www/website.com/public_html/functions.php
). I am connecting to the database like this:
function connect(){
$config = parse_ini_file('/var/www/website.com/db.ini');
$con = mysqli_connect("localhost",$config['username'],$config['password'],$config['db']);
if(!$con){
die("Failed to connect to Database");
}
return $con;
}
Where the /var/www/website.com/db.ini
is
username=user123
password=pass123
db=mydb
with permissions:
-rw-r--r-- 1 root root 84 /var/www/website.com/db.ini
The PHP will be run by either www-data
or root
.
The root of website.com
is /var/www/website.com/public_html/
.
Is this the best way to connect to a database using PHP from a security point of view? I am also making this code open source.
2 Answers 2
Your approach looks good.
You are storing the credentials in a separate configuration file instead of having them written inline in the source code. This makes it safe when sharing the code with others and protects the credentials in case a misconfiguration lets the plain PHP code be printed out (which happens quite often).
The config file is outside the public document root, therefore it cannot be directly accessed by a user of the web application, unless there is another vulnerability (e.g. a directory traversal flaw).
In any case you should avoid running the server as
root
. Otherwise the permission model is worthless, sinceroot
can read and write to any file.
Note that you don't have to deal with parsing the credentials in your code at all - you can instead specify them as PHP runtime settings in the server configuration, as explained here.
Also see:
-
5The file does not have minimal permissions. It could be chgrp'ed to www-data and chmod'ed 640.Oskar Skog– Oskar Skog2017年02月28日 15:19:52 +00:00Commented Feb 28, 2017 at 15:19
-
I would go further than saying "you should avoid". You should never run a web server as root. It should run as its own user, and this is the default for most (if not all) package-based installations.Polynomial– Polynomial2019年07月21日 15:04:21 +00:00Commented Jul 21, 2019 at 15:04
I am skeptical of this -rw-r--r-- 1 root root
approach. The secure way to do it would be
- Make the file
-r-------- 1 root root
i.e. readable only by userroot
- Start your app as
root
, read the credentials and connect then immediatelysetuid()
towww-data
. So anyone who compromises the app cannot read the file, even via a directory traversal attack, unless of course they find another means of obtainingroot
in which case it's game over anyway. This should be possible in PHP.
This is the same mechanism web servers use to bind to port 80, which is a privileged port.
root
. I would also think you could probably get by with a -r--r--r-- (444) permission as opposed to -rw-r--r-- (644).www-data
, permissions are not right for the db config file. Any specific reason to run it as root?