当PHP应用程序建立数据库连接时,当然通常需要传递登录名和密码。如果我对我的应用程序使用一个最小权限的登录,那么PHP需要知道这个登录名和密码。保护密码的最好方法是什么?只在PHP代码中编写它似乎不是一个好主意。


当前回答

最安全的方法是在PHP代码中完全不指定这些信息。

如果你使用Apache,这意味着在httpd.conf或虚拟主机文件中设置连接细节。如果你这样做,你可以不带参数地调用mysql_connect(),这意味着PHP永远不会输出你的信息。

这是你在这些文件中指定这些值的方法:

php_value mysql.default.user      myusername
php_value mysql.default.password  mypassword
php_value mysql.default.host      server

然后像这样打开mysql连接:

<?php
$db = mysqli_connect();

或者像这样:

<?php
$db = mysqli_connect(ini_get("mysql.default.user"),
                     ini_get("mysql.default.password"),
                     ini_get("mysql.default.host"));

其他回答

之前我们将DB user/pass存储在一个配置文件中,但后来进入了偏执模式——采用了深度防御策略。

如果您的应用程序被泄露,用户将拥有对您的配置文件的读访问权,因此黑客就有可能读取这些信息。配置文件也可能在版本控制中被捕获,或者在服务器中被复制。

我们已经切换到在Apache VirtualHost中设置的环境变量中存储user/pass。这个配置只能由根用户读取——希望您的Apache用户不是以根用户身份运行。

这样做的缺点是,现在密码在一个全局PHP变量中。

为了降低这种风险,我们有以下预防措施:

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.

如果谈论的是数据库密码,而不是来自浏览器的密码,标准的做法似乎是将数据库密码放在服务器上的PHP配置文件中。

您只需要确保包含密码的php文件具有适当的权限即可。也就是说,它应该是可读的只有web服务器和您的用户帐户。

将数据库密码放在一个文件中,使其对提供文件的用户只读。

除非您有某种方法只允许php服务器进程访问数据库,否则这几乎就是您所能做的全部工作。

最好的办法是根本不存储密码! 例如,如果您在Windows系统上,并连接到SQL Server,则可以使用集成身份验证来使用当前进程的标识连接到数据库,而不需要密码。

如果您确实需要使用密码连接,首先对其进行加密,使用强加密(例如使用AES-256,然后保护加密密钥,或使用非对称加密并让操作系统保护证书),然后将其存储在具有强acl的配置文件中(在web目录之外)。

我们是这样解决的:

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.