CWE-245: J2EE Bad Practices: Direct Management of Connections

Description

The J2EE application directly manages connections, instead of using the container's connection management facilities.

Submission Date :

July 19, 2006, midnight

Modification Date :

2023-06-29 00:00:00+00:00

Organization :

MITRE
Extended Description

The J2EE standard forbids the direct management of connections. It requires that applications use the container's resource management facilities to obtain connections to resources. Every major web application container provides pooled database connection management as part of its resource management framework. Duplicating this functionality in an application is difficult and error prone, which is part of the reason it is forbidden under the J2EE standard.

Example Vulnerable Codes

Example - 1

In the following example, the class DatabaseConnection opens and manages a connection to a database for a J2EE application. The method openDatabaseConnection opens a connection to the database using a DriverManager to create the Connection object conn to the database specified in the string constant CONNECT_STRING.


conn = DriverManager.getConnection(CONNECT_STRING);try {} catch (SQLException ex) {...}
private static final String CONNECT_STRING = "jdbc:mysql://localhost:3306/mysqldb";private Connection conn = null;public DatabaseConnection() {}public void openDatabaseConnection() {}// Member functions for retrieving database connection and accessing database...public class DatabaseConnection {}

The use of the DriverManager class to directly manage the connection to the database violates the J2EE restriction against the direct management of connections. The J2EE application should use the web application container's resource management facilities to obtain a connection to the database as shown in the following example.




InitialContext ctx = new InitialContext();DataSource datasource = (DataSource) ctx.lookup(DB_DATASRC_REF);conn = datasource.getConnection();
try {} catch (NamingException ex) {...}} catch (SQLException ex) {...}
private static final String DB_DATASRC_REF = "jdbc:mysql://localhost:3306/mysqldb";private Connection conn = null;public DatabaseConnection() {}public void openDatabaseConnection() {}// Member functions for retrieving database connection and accessing database...public class DatabaseConnection {}

Related Weaknesses

This table shows the weaknesses and high level categories that are related to this weakness. These relationships are defined to give an overview of the different insight to similar items that may exist at higher and lower levels of abstraction.

Visit http://cwe.mitre.org/ for more details.