Question

I have JSP web application deployed in Tomcat7 server that use MySQL as a database. In database connection I'm currently providing clear text username and password as below.

Connection conn = DriverManager.getConnection("jdbc:mysql://hostname:3306/schema", "user", "password");

As a security requirement I cannot use plain text passwords in my code and I cannot use configuration files to store information ether so everything has to be in a database somewhere.

Q1 As for this issue can I provide a hashed input for password field in connection string.?

Q2 If I can't use file based configuration method which would be the best way to store sensitive information.?

Was it helpful?

Solution

The best approach is to define JDBC datastore in tomcat and then look it up in your web application. Following samples are shamelessly copied from tomcat documentation. This way you do not have any passwords in your applicaion. The configuration is done by tomcat administrator, not by web application developer.

Context:

<Resource name="jdbc/TestDB" auth="Container" type="javax.sql.DataSource"
           maxActive="100" maxIdle="30" maxWait="10000"
           username="javauser" password="javadude" 
           driverClassName="com.mysql.jdbc.Driver"
           url="jdbc:mysql://localhost:3306/javatest"/>

web.xml

<resource-ref>
  <description>DB Connection</description>
  <res-ref-name>jdbc/TestDB</res-ref-name>
  <res-type>javax.sql.DataSource</res-type>
  <res-auth>Container</res-auth>
</resource-ref>

test.jsp

<sql:query var="rs" dataSource="jdbc/TestDB">
   select id, foo, bar from testdata
</sql:query>

servlet

Context initContext = new InitialContext();
Context envContext  = (Context)initContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup("jdbc/TestDB");
Connection conn = ds.getConnection();

Regarding your security requirements: this is harder, because the password is plaintext there as well. You can limit access rights so only web container can read it. Encrypting password will not work with symmetrical ciphers because attacker can get them as well. And asymmetrical ciphers - he can get decode key too. So you must set up the environment that attacker will not see content of the configuration files. If he is root, everything is lost anyway.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top