Question

In the web-application I'm developing I currently use a naive solution when connecting to the database:

Connection c = DriverManager.getConnection("url", "username", "password");

This is pretty unsafe. If an attacker gains access to the sourcecode he also gains access to the database itself. How can my web-application connect to the database without storing the database-password in plaintext in the sourcecode?

Was it helpful?

Solution

You can store the connection string in Web.config or App.config file and encrypt the section that holds it. Here's a very good article I used in a previous project to encrypt the connection string:

http://www.ondotnet.com/pub/a/dotnet/2005/02/15/encryptingconnstring.html

OTHER TIPS

In .NET, the convention is to store connectionstrings in a separate config file.

Thereon, the config file can be encrypted.

If you are using Microsoft SQL Server, this all becomes irrelevant if you use a domain account to run the application, which then uses a trusted connection to the database. The connectionstring will not contain any usernames and passwords in that case.

I can recommend these techniques for .NET programmers:

  • Encrypt password\connection string in config file
  • Setup trusted connection between client and server (i.e. use windows auth, etc)

Here is useful articles from CodeProject:

Unless I am missing the point the connection should be managed by the server via a connection pool, therefore the connection credentials are held by the server and not by the app.

Taking this further I generally build to a convention where the frontend web application (in a DMZ) only talks to the DB via a web service (in domain), therefore providing complete separation and enhanced DB security.

Also, never give priviliges to the db account over or above what is essentially needed.

An alternative approach is to perform all operations via stored procedures, and grant the application user access only to these procs.

Assuming that you are using MS SQL, you can take advantage of windows authentication which requires no ussername/pass anywhere in source code. Otherwise I would have to agree with the other posters recommending app.config + encryption.

  1. Create an O/S user
  2. Put the password in an O/S environment variable for that user
  3. Run the program as that user

Advantages:

  1. Only root or that user can view that user's O/S environment variables
  2. Survives reboot
  3. You never accidentally check password in to source control
  4. You don't need to worry about screwing up file permissions
  5. You don't need to worry about where you store an encryption key
  6. Works x-platform
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top