Hard coding sensitive information, such as passwords or encryption keys can expose the information to attackers. Anyone who has access to the executable or dynamic library files can examine them for strings or other critical data, revealing the sensitive information. Leaking data protected by International Traffic in Arms Regulations (ITAR) or the Health Insurance Portability and Accountability Act (HIPAA) can also have legal consequences. Consequently, programs must not hard code sensitive information.
Hard coding sensitive information also increases the need to manage and accommodate changes to the code. For example, changing a hard-coded password in a deployed program may require distribution of a patch [Chess 2007].
Noncompliant Code Example (Hard-Coded Database Password)
The user name and password fields in the SQL connection request are hard coded in this noncompliant code example:
public final Connection getConnection() throws SQLException { return DriverManager.getConnection( "jdbc:mysql://localhost/dbName", "username", "password"); }
Note that the one- and two-argument java.sql.DriverManager.getConnection()
methods can also be used incorrectly.
Compliant Solution
This compliant solution reads the user name and password from a configuration file located in a secure directory:
public final Connection getConnection() throws SQLException { String username; String password; // Username and password are read at runtime from a secure config file return DriverManager.getConnection( "jdbc:mysql://localhost/dbName", username, password); }
It is also permissible to prompt the user for the user name and password at runtime.
When possible, sensitive information such as passwords should be stored in character arrays rather than strings because the Java Virtual Machine may retain strings long after they are no longer needed. However, this example uses strings because DriverManager.getConnection()
requires them.
Risk Assessment
Hard coding sensitive information exposes that information to attackers. The severity of this rule can vary depending on the kind of information that is disclosed. Frequently, the information disclosed is password or key information, which can lead to remote exploitation. Consequently, a high severity rating is given but may be adjusted downwards according to the nature of the sensitive data.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
MSC31-J | High | Probable | Medium | P12 | L1 |
Automated Detection
Tool | Version | Checker | Description |
---|
Related Guidelines
SEI CERT Oracle Coding Standard for Java | MSC03-J. Never hard code sensitive information |
Hard-coded Password [XYP] | |
CWE-259, Use of Hard-Coded Password |
Bibliography
Section 11.2, "Outbound Passwords: Keep Passwords out of Source Code" | |
"Unsafe Mobile Code: Database Access" |