Description
Passwords embedded in code can be exposed during a security incident. They may also be committed to source repositories, such as GitHub or GitLab, where an attacker can obtain them and gain unauthorized access.
Read passwords from a secret store or access-controlled runtime configuration instead of embedding them in code.
Potential impact
- Password exposure: Leaked code or credentials committed to version control can reveal passwords.
- Automated attacks: Attackers can extract the passwords and use them in automated login attempts.
- Difficult rotation: Changing an embedded password requires a code change and redeployment.
Remediation
-
Keep passwords out of code
- Read them from a secret store or runtime configuration, and replace any exposed passwords.
-
Use an appropriate secret store
- Store passwords with a secret-management service, such as HashiCorp Vault, and restrict access. AWS KMS and Google Cloud KMS manage encryption keys; distinguish this from password storage.
-
Protect environment variables and configuration files
- If passwords are supplied through
.envfiles or OS environment variables, keep actual values out of the repository and restrict access to the files and runtime environment.
- If passwords are supplied through
Examples
Before
java
import java.security.KeyStore;
public class InsecurePasswordExample {
public void loadKeyStore() throws Exception {
KeyStore keyStore = KeyStore.getInstance("JKS");
keyStore.load(null, "hardcoded_password".toCharArray()); // Hard-coded password
}
}
After
java
import java.security.KeyStore;
public class SecurePasswordExample {
public void loadKeyStore() throws Exception {
String password = System.getenv("KEYSTORE_PASSWORD"); // Read the password from an environment variable
if (password == null) {
throw new SecurityException("Keystore password is not set");
}
KeyStore keyStore = KeyStore.getInstance("JKS");
keyStore.load(null, password.toCharArray());
}
}
Explanation:
- Before: The password is embedded in
keyStore.load(null, "hardcoded_password".toCharArray());. - After:
System.getenv("KEYSTORE_PASSWORD")reads a runtime value. Access to the environment variable must also be restricted.
In both examples, load(null, ...) initializes an empty keystore. It does not open an existing keystore file.