What is the (most?) secure way to handle database connections in a web application?
I have a web application written in Perl using PostgreSQL.
When accessing the PostgreSQL database I need to supply both username and password. In order to have the password available for unattended start-ups of the system I need have that password embedded in my application or in a configu开发者_C百科ration file or as an environment variable configured in Apache.
In either case I have to have the password in clear text format somewhere.
How is it done in real web sites?
The most secure way to do it is to have a configuration file, and put that outside the public folders.
- Make sure the password is somewhere the web server is never going to serve. If possible put it outside the webroot; if that's not possible,
- Make sure the file containing the password is readable only by the user the web server runs as, and not writeable by anyone
- Rotate it regularly, to minimise the impact if it does somehow leak
- Make sure that the database user you're using has minimal permissions. Eg, for a Wordpress installation, create an account just for Wordpress to use, and give it access only to the databases it actually needs
- Configure the database to only accept connections from the web server, to minimize the impact of a leak by preventing the attacker from being able to use that password from just any old random node on the net
You can "trust" your Web server's IP (or the localhost, if it's the same node) in your PostgreSQL's pg_hba.conf, and use no password at all. At least, I don't think it's less secure than storing the database password somewhere in the file system of your Web server.
Of course, you can try encrypting and obfuscating the password somehow. But this security through obscurity is not really a barrier for someone who has managed to get into your Web server, especially when all the Perl source code is there to read.
You can store the password in ~/.pgpass (for the web server user, of course). This is obviously not safe in shared hosting where the same user is used for many different websites, but if you have a dedicated setup it often works very well. See http://www.postgresql.org/docs/current/static/libpq-pgpass.html.
The important thing is to store it outside the general web tree.
Use Firewall IP:port filter at PostgreSQL Server and limit the access to only IPs of your web-server.
精彩评论