...
Code Block | ||
---|---|---|
| ||
class HardcodedPassword { String password = new String("guest"); public static void main(String[] args) { //.. } } |
A malicious user can use the javap -c HardcodedPassword
command to disassemble the class and discover the hardcoded password. The output of the disassembler as shown below, reveals the password guest
in cleartext.
Code Block |
---|
Compiled from "HardcodedPassword.java" class HardcodedPassword extends java.lang.Object{ java.lang.String password; HardcodedPassword(); Code: 0: aload_0 1: invokespecial #1; //Method java/lang/Object."<init>":()V 4: aload_0 5: new #2; //class java/lang/String 8: dup 9: ldc #3; //String guest 11: invokespecial #4; //Method java/lang/String."<init>":(Ljava/lang/String;)V 14: putfield #5; //Field password:Ljava/lang/String; 17: return public static void main(java.lang.String[]); Code: 0: return } |
...
This compliant solution uses a char
array to store the password after it is retrieved from an external file existing in a secure directory. The password is immediately cleared after use. This limits , limiting the exposure time.
Code Block | ||
---|---|---|
| ||
class Password { public static void main(String[] args) throws IOException { char[] password = new char[100]; BufferedReader br = new BufferedReader(new InputStreamReader( new FileInputStream("passwordcredentials.txt"))); // Reads the password into the char array, returns the number of bytes read int n = br.read(password); // Decrypt password, perform operations for(int i = n - 1; i >= 0; i--) { // Manually clear out the password immediately after use password[i] = 0; } br.close(); } } |
To further limit the exposure time of the sensitive password, follow the guideline MSC10-J. Limit the lifetime of sensitive data by replacing BufferedReader
with a direct NIO buffer.
Noncompliant Code Example (hardcoded database password)
This noncompliant code example hardcodes the user name and password fields in the SQL connection request.
...
Note that the one and two argument java.sql.DriverManager.getConnection()
methods may also be used incorrectly. Applets that contain similar code are also noncompliant unacceptable because they may be executed in untrusted environments.
...
Hardcoding sensitive information allows a malicious user an attacker to glean the information.
...