Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: secure 1st CS if exception thrown

...

This noncompliant code example reads user name and password information from the console and stores the password as a String object object. The credentials remain exposed until the garbage collector reclaims the memory associated with this String. While this method explicitly invokes System.gc() after verification, it is possible for the password to to this String.

Code Block
bgColor#FFCCCC
class Password {
  public static void main (String args[]) throws IOException {
    Console c = System.console();
    if (c == null) {
      System.err.println("No console.");
      System.exit(1);
    }

    String username = c.readLine("Enter your user name: ");
    String password = c.readLine("Enter your password: ");

    if (!verify(username, password)) {
      throw new SecurityException("Invalid Credentials"); 
    }

    // User is authorized, continue...
  }

  // Dummy verify method, always returns true   
  private static final boolean verify(String username, String password) {
    return true;
  }
}

Noncompliant Code Example (System.gc())

This noncompliant code example attempts to erase the password string by explicitly invoking garbage collection after verification. However, the password might still not be garbage-collected. For example, this can happen if the password string matches a pre-existing string in the program.

...

The Console.readPassword() method allows the password to be returned as a sequence of characters rather than as a String object. Because the password is never interned as a String, it will not survive garbage collection even if it matches another string. Consequently, the programmer can clear the password from the array immediately after use. This method .

The Console.readPassword() method also disables echoing of the password to the console.

...