Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Hardcoding Hard coding sensitive information, such as passwords, is an extremely dangerous practice. Doing so can have the following ominous effects -

  • The sensitive information can become accessible to whoever has access to the source code, for example, the developers.
  • Wiki Markup
    Once the system goes into production, it can become unwieldy to manage and accommodate changes to the code. For instance, a change in password will have to be communicated using a patch \[[Chess 07|AA. Java References#Chess 07]\].
  • In certain cases, it can also violate the fundamental principle of recalling the memory used to store the sensitive information as soon as the required operation has concluded. A carefully administered heap dump or application monitoring through a JVM debugger can expose the sensitive information if it persists over an extended period of time.
  • Malicious users may use decompilation techniques to resurrect the hardcoded sensitive information. This is a critical security vulnerability.

, server IP addresses, and encryption keys can expose the information to attackers. Anyone who has access to the class files can decompile them and discover 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

This noncompliant code example uses a password field instantiated as a String. includes a hard-coded server IP address in a constant String:

Code Block
bgColor#FFcccc

class HardcodedIPaddress {
  String passwordipAddress = new String("guest172.16.254.1");
  public static void main(String[] args) {
    //...
  }
}

Notably, when the password is no longer required, it has to be left to the mercy of the garbage collector. This is because String objects are immutable and continue to persist even after dereferencing them, until the garbage collector performs its job.

Secondly, a malcious A malicious user can use the javap -c HardcodedIPaddress command to disassemble the class and uncover the hardcoded passworddiscover the hard-coded server IP address. The output of the disassembler as shown below, makes available the password guest in cleartext.reveals the server IP address 172.16.254.1 in clear text:

Code Block

Compiled from "HardcodedIPaddress.java"
class HardcodedIPaddress extends java.lang.Object{
java.lang.String passwordipAddress;

HardcodedIPaddress();
  Code:
   0:	     aload_0
   1:	invokespecial	     invokespecial     #1; //Method java/lang/Object."<init>":()V
   4:	     aload_0
   5:	new	     new   #2; //class java/lang/String
   8:	     dup
   9:	ldc	     ldc   #3; //String guest172.16.254.1
   11:	invokespecial	    invokespecial     #4; //Method java/lang/String."<init>":(Ljava/lang/String;)V
   14:	putfield	    putfield    #5; //Field passwordipAddress:Ljava/lang/String;
   17:	    return

public static void main(java.lang.String[]);
  Code:
   0:	     return

}

Compliant Solution

This compliant solution uses a char array to store the password after it is retrieved from an external file. The password is immediately cleared out after use. This limits the exposure time.retrieves the server IP address from an external file located in a secure directory, as recommended by FIO00-J. Do not operate on files in shared directories. It reads the file in compliance with FIO10-J. Ensure the array is filled when using read() to fill an array. Exposure of the IP address is further limited by storing it in a char array rather than a java.lang.String, and by clearing the server IP address from memory immediately after use.

Code Block
bgColor#ccccff

class PasswordIPaddress {
  public static void main(String[] args) throws IOException {
    char[] passwordipAddress = new char[100];	
    int offset = 0;
    int charsRead = 0;
    BufferedReader br = null;
    try {
      br = new BufferedReader(new InputStreamReader(
             new FileInputStream("passwordserveripaddress.txt")));
      while ((charsRead = br.read(ipAddress, offset, ipAddress.length - offset))
        // reads the password into the char array, returns the number of bytes read 
!= -1) {
        offset += charsRead;
        intif n(offset >= bripAddress.read(password);length) {
          break;
        }
      }
      
      // decrypt password, perform operations
 ... Work with IP address

    } finally {
      Arrays.fill(ipAddress,  (byte) 0);
      for(int i= n - 1;i >= 0;i--)  // manually clear out the password immediately after use 
      password[i] = 0;	 
    br.close();
    }
}

Risk Assessment

br.close();
    }
  }
}

To further limit the exposure time of the sensitive server IP address, replace BufferedReader with a direct native input/output (NIO) buffer, which can be cleared immediately after use.

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:

Code Block
bgColor#FFcccc
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:

Code Block
bgColor#ccccff
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 dataHardcoding sensitive information can lead to critical security vulnerabilities.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

MSC31

MSC03-J

high

High

probable

Probable

medium

Medium

P12

L1

Automated Detection

...

TODO

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

Other Languages

...

ToolVersionCheckerDescription
CodeSonar

Include Page
CodeSonar_V
CodeSonar_V

JAVA.HARDCODED.PASSWD
JAVA.MISC.SD.EXT

Hardcoded Password (Java)
Sensitive Data Written to External Storage (Java)

Coverity7.5

HARDCODED_CREDENTIALS
CONFIG
FB.DMI_CONSTANT_DB_ PASSWORD
FB.DMI_EMPTY_DB_PASSWORD

Implemented
Fortify1.0

Password_Management
Password_Management__Hardcoded_Password

Partially implemented
Parasoft Jtest
Include Page
Parasoft_V
Parasoft_V
CERT.MSC03.HCCS
CERT.MSC03.HCCK
CERT.MSC03.AHCA
Avoid passing hardcoded usernames/passwords/URLs to database connection methods
Avoid using hard-coded cryptographic keys
Avoid hard-coding the arguments to certain methods
PMD1.0AvoidUsingHardCodedIPPartially implemented
SonarQube
Include Page
SonarQube_V
SonarQube_V
S1313
S2068
Partially implemented

Related Vulnerabilities

GERONIMO-2925 describes a vulnerability in the WAS CE tool, which is based on Apache Geronimo. It uses the Advanced Encryption Standard (AES) to encrypt passwords but uses a hard-coded key that is identical for all the WAS CE server instances. Consequently, anyone who can download the software is provided with the key to every instance of the tool. This vulnerability was resolved by having each new installation of the tool generate its own unique key and use it from that time on.

Related Guidelines

...

ISO/IEC TR 24772:2010

Hard-coded Password [XYP]

MITRE CWE

CWE-259, Use of Hard-Coded Password
CWE-798, Use of Hard-Coded Credentials

Android Implementation Details

Hard-coded information can be easily obtained on Android by using the apktool to decompile an application or by using dex2jar to convert a dex file to a jar file.

Bibliography

[Chess 2007]

Section 11.2, "Outbound Passwords: Keep Passwords out of Source Code"

[Fortify 2008]

"Unsafe Mobile Code: Database Access"

[Gong 2003]

Section 9.4, "Private Object State and Object Immutability"


...

Image Added Image Added Image Added

References

Wiki Markup
\[[Gong 03|AA. Java References#Gong 03]\] 9.4 Private Object State and Object Immutability
\[[Chess 07|AA. Java References#Chess 07]\] 11.2 Outbound Passwords: Keep Passwords out of Source Code
\[[MITRE 09|AA. Java References#MITRE 09]\] [CWE ID 259|http://cwe.mitre.org/data/definitions/259.html] "Hard-Coded Password"

FIO33-J. Exclude user input from format strings      08. Input Output (FIO)      08. Input Output (FIO)