Description
Embedding a password in source code exposes it to anyone who can read the repository or deployed code.
Potential impact
An exposed password can be used in login attempts, including automated ones. Changing an embedded password also requires a code change and redeployment.
Remediation
- Read passwords from a secret store such as HashiCorp Vault or from access-controlled runtime configuration. AWS KMS and Google Cloud KMS manage encryption keys.
- Keep actual
.envand environment variable values out of version control and restrict who can read them. Replace exposed passwords and update the services that use them.
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());
}
}
The revised example stops if KEYSTORE_PASSWORD is unset. Both examples call load(null, ...) to initialize an empty keystore.