Connection String Injection

Example 1: Java

Vulnerable Code:

javaCopy codeString connStr = "jdbc:mysql://localhost:3306/mydb?user=" + user + "&password=" + password;
Connection conn = DriverManager.getConnection(connStr);

Reason for vulnerability: User input is directly used in the connection string, allowing injection.

Fixed Code:

javaCopy codeString connStr = "jdbc:mysql://localhost:3306/mydb";
Connection conn = DriverManager.getConnection(connStr, user, password);

Reason for fix: Use separate parameters for user credentials.

Example 2: C#

Vulnerable Code:

csharpCopy codestring connStr = "Server=myServerAddress;Database=myDataBase;User Id=" + user + ";Password=" + password + ";";
SqlConnection conn = new SqlConnection(connStr);
conn.Open();

Reason for vulnerability: User input is directly used in the connection string, allowing injection.

Fixed Code:

csharpCopy codestring connStr = "Server=myServerAddress;Database=myDataBase";
SqlConnection conn = new SqlConnection(connStr);
conn.Credentials = new SqlCredential(user, password);
conn.Open();

Reason for fix: Use separate parameters for user credentials.

Last updated