Reading passwords using System.console ()

There is a security note in javadoc for the java.io.Console class:

Safety Notice. If an application needs to read a password or other protected data, it should use readPassword () or readPassword (String, Object ...) and manually zero out the returned character array after processing to minimize the lifetime of sensitive data in memory.

 Console cons;
 char[] passwd;
 if ((cons = System.console()) != null &&
     (passwd = cons.readPassword("[%s]", "Password:")) != null) {
     ...
     java.util.Arrays.fill(passwd, ' ');
 }

I do not understand why you need such drastic measures? When a method that reads a password pops off the stack, the array object referenced by the local passwd variable will have the right to garbage collection. No one (even an attacker) can get a reference to this array, assuming that the array does not go beyond the scope of the method.

So, why do you need to change the array (erasing the password) when you know that it will be eligible for the GC as soon as the method pops out of the stack? They say:

to minimize the lifetime of sensitive data in memory

but for me, this programming style seems pretty ... desperate.

+4
source share
4 answers

, , , . , , , .

.

: :

Java:

public class Main {
    private static void readPassword() {
        char[] password = System.console().readPassword();
    }

    public static void main(String[] args) throws Exception {
        readPassword();
        Thread.sleep(1000 * 3600);
    }
}
  • javac Main.java
  • java Main
  • (, topsecret), enter

, PID (, 1000) jmap:

jmap -dump:format=b,file=dump.bin 1000

VisualVM , "/" .

OQL :

select a from char[] a where a.length == 9 && a[0] == 't'

, , "topsecret", . , , , , .

Visualvm

, , , , .

+11

, , . , GC "" ( ), - , , , , .

+8

char [] String ?

, , , , . , - GC , , . , , char [] .

+2

, , , , passwd, . ( ) , , .

, : Java , , .

, , , , , ( ) .

, , , , , :

  • JVM

    • ( , )
    • . .
    • , (, ).
    • . , .
    • , .
    • , . ...
    • , . , , DRAM ()
    • , , , Cisco

, , , , . , , , , , , .

Therefore, I find that using char[]for passwords is rarely useful. By the way, this opinion is apparently shared by the JDBC API developers, who require connection passwords to be passed asString , which prevents them from being cleared after the connection is established.

However, there may be cases where the confidentiality of the main memory cannot be guaranteed, as well as mitigating the damage by keeping the vulnerability window as small as possible. Your threat model should answer if this is so.

+2
source

Source: https://habr.com/ru/post/1569080/


All Articles