views:

790

answers:

5

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?

+15  A: 

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

Julio César
+1  A: 

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:

aku
+5  A: 

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.

Jon Limjap
+1  A: 

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.

stjohnroe
+1  A: 

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.

Andrew