Here is a vulnerable Java code snippet that is susceptible to Hardcoded Credentials vulnerability:
🥺 Vulnerable Code
import java.sql.Connection;
import java.sql.DriverManager;
public class VulnerableCode {
public static void main(String[] args) {
// VULNERABLE: Hardcoded credentials
String username = "admin";
String password = "password";
try {
// Connect to database using hardcoded credentials
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test_db", username, password);
System.out.println("Connected to database!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
In this code, the “username” and “password” variables contain hardcoded values that are used to connect to a database. This is a vulnerable practice because it exposes the credentials in plain text, making them easily accessible to attackers.
😎 Secure Code
Here is a modified version of the code that uses AWS Secrets Manager to securely store and retrieve the credentials:
import java.sql.Connection;
import java.sql.DriverManager;
import com.amazonaws.services.secretsmanager.AWSSecretsManager;
import com.amazonaws.services.secretsmanager.AWSSecretsManagerClientBuilder;
import com.amazonaws.services.secretsmanager.model.GetSecretValueRequest;
import com.amazonaws.services.secretsmanager.model.GetSecretValueResult;
import com.amazonaws.services.secretsmanager.model.ResourceNotFoundException;
import org.json.JSONObject;
public class SecureCode {
public static void main(String[] args) {
// Create Secrets Manager client
AWSSecretsManager client = AWSSecretsManagerClientBuilder.defaultClient();
// Securely retrieve credentials from Secrets Manager
String secretName = "database_credentials";
String region = "us-west-2";
GetSecretValueRequest getSecretValueRequest = new GetSecretValueRequest()
.withSecretId(secretName)
.withVersionStage("AWSCURRENT");
GetSecretValueResult getSecretValueResult = null;
try {
getSecretValueResult = client.getSecretValue(getSecretValueRequest);
} catch (ResourceNotFoundException e) {
System.out.println("The requested secret " + secretName + " was not found");
}
String secretString = getSecretValueResult.getSecretString();
JSONObject secret = new JSONObject(secretString);
String username = secret.getString("username");
String password = secret.getString("password");
try {
// Connect to database using securely retrieved credentials
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test_db", username, password);
System.out.println("Connected to database!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
In this code, the “username” and “password” variables are securely retrieved from AWS Secrets Manager and are not exposed in plain text. This is a more secure practice than using hardcoded credentials.