How can I ensure the destruction of a String objec

2019-01-11 00:22发布

问题:

An empoyee at my company needs to modify data from a SQL Server database through a program I made. The program used Windows authentication at first, and I asked the DBAs to give this specific user write access to said database.

They were not willing to do this, and instead gave write access to my Windows user account.

Since I trust the guy but not enough to let him work 90 minutes with my session open, I'll just add a login prompt to my program, asking for a username and password combination, and log in to SQL Server with it. I'll log in, and trust my application to let him do only what he needs to.

This, however, raises a small security risk. The password fields tutorial over SunOracle's site states that passwords should be kept the minimum amount of time required in memory, and to this end, the getPassword method returns a char[] array that you can zero once you're done with it.

However, Java's DriverManager class only accepts String objects as passwords, so I won't be able to dispose of the password as soon as I'm done with it. And since my application is incidentally pretty low on allocations and memory requirements, who knows how long it'll survive in memory? The program will run for a rather long time, as stated above.

Of course, I can't control whatever the SQL Server JDBC classes do with my password, but I hoped I could control what I do with my password.

Is there a surefire way to destroy/zero out a String object with Java? I know both are kind of against the language (object destruction is non-deterministic, and String objects are immutable), and System.gc() is kind of unpredictable too, but still; any idea?

回答1:

So, here's the bad news. i'm surprised no one has mentioned it yet. with modern garbage collectors, even the whole char[] concept is broken. regardless of whether you use a String or a char[], the data can end up living in memory for who-knows-how-long. why is that? because modern jvms use generational garbage collectors which, in short, copy objects all over the place. so, even if you use a char[], the actual memory it uses could get copied to various locations in the heap, leaving copies of the password everywhere it goes (and no performant gc is going to zero out old memory). so, when you zero out the instance you have at the end, you are only zeroing out the latest version in memory.

long story, short, there's no bulletproof way to handle it. you pretty much have to trust the person.



回答2:

I can only think of a solution using reflection. You can use reflection to invoke the private constructor that uses a shared character array:

  char[] chars = {'a', 'b', 'c'};
  Constructor<String> con = String.class.getDeclaredConstructor(int.class, int.class, char[].class);
  con.setAccessible(true);
  String password = con.newInstance(0, chars.length, chars);
  System.out.println(password);

  //erase it
  Arrays.fill(chars, '\0');
  System.out.println(password);

Edit

For anyone thinking this is a failproof or even useful precaution, I encourage you to read jtahlborn's answer for at least one caveat.



回答3:

if you absolutely must, keep a WeakReference to the string, and keep gobbling memory until you force garbage collection of the string which you can detect by testing if the weakreference has become null. this may still leave the bytes in the process address space. may be a couple more churns of the garbage collector would give you comfort? so after your original string weakreference got nulled, create another weakreference and churn until it is zeroed which would imply a full garbage collection cycle was done.

somehow, i have to add LOL to this even though my answer above is entirely serious :)



回答4:

You can change the value of the inner char[] using reflection.

You must be careful to either change it with an array of the same length, or to also update the count field. If you want to be able to use it as an entry in a set or as a value in map, you will need to recalculate the hash code and set the value of the hashCode field.

That being said, the minimal code to achieve this is

        String password = "password";

        Field valueField = String.class.getDeclaredField("value");
        valueField.setAccessible(true);
        char[] chars  = (char[]) valueField.get(password);

        chars[0] = Character.valueOf('h');

        System.out.println(password);


回答5:

I am not sure on the DriverManager class.
Generally speaking, you are right, the recomendation is to store the password in char arrays and to explicitely clear the memory after usage.
The most common example:

KeyStore store = KeyStore. getInstance(KeyStore, getDefaultType()) ;
char[] password = new char[] {'s','e','c','r','e','t'};
store .load(is, password );
//After finished clear password!!!
Arrays. fill(password, '\u0000' ) ;

In the JSSE and JCA the design had exactly this in mind. That is why the APIs expect a char[] and not a String.
Since, as you very well know Strings are immutable, the password is eligible for future garbage collection and you can not reset it afterwards. This can cause security risks by malicious programs that snoop memory areas.
I do not think in this case you are looking into there is a work around.
Actually there is a similar question here:
Why Driver Manager not use char arrays?
but there is no clear answer.
It appears that the concept is that the password is already stored in a properties file (there is already a DriverManager constructor accepting properties) and so the file itself already imposes a bigger risk than the actual loading the password from a file to a string.
Or the designers of the API had some assumptions on the safety of the machine accessing the DB.
I think the safest option would be to try to look into, if it is possible, on how the DriverManager uses the password i.e. does it hold on to an internal reference etc.



回答6:

so I won't be able to dispose of the password as soon as I'm done with it.

Why not?

If you're getting a connection via

Driver.getConnection 

you just have to pass the password and let it be gc'ed.

void loginScreen() {
   ... 
   connect( new String( passwordField.getPassword() ) );
   ...
}
...
void connect( String withPassword ) { 
    connection = DriverManager.getConnection( url, user, withPassword );
    ...
}//<-- in this line there won't be any reference to your password anymore.

When the control return from the connect method, there is no longer a reference for your password. No one can use it anymore. If you need to create a new session, you have to invoke "connect" again with a new password. The reference to the object that holds your information is lost.



回答7:

If the string is not being held onto by JDBC driver manager (a big if), I wouldn't worry about forcing its destruction. A modern JVM, still runs the garbage collection fairly promptly even with plenty of available memory. The issue is whether garbage collection is effective "secure erase". I doubt that it is. I would guess that it simply forgets the reference to that memory location and doesn't zero anything out.



回答8:

There's no regular way of forcing garbage collection. It is possible through a native call but I don't know if it would work for Strings, seeing as they are pooled.

Maybe an alternative approach will help? I'm not that familiar with SQL Server but in Oracle the practice is to have user A own the database objects and a set of stored procedures, and user B owning nothing but given run permission on the procedures. This way the password isn't really a problem anymore.

In your case, it will be your user who owns all the database object and stored procedures and your employee will need run privileges to the stored procs, which the DBAs will hopefully be less reluctant to give.



回答9:

Interesting question. Some googeling revealed this: http://securesoftware.blogspot.com/2009/01/java-security-why-not-to-use-string.html. According to the comment, it won't make a difference.

What happens, if you dont store the String in a variable but pass it via new String(char[])?



标签: java security