Does using reflection to scrub a String
make using String
as safe as using char[]
for passwords?
From a security aspect, it is
There are two potential safety concerns:
The String may share its backing array with other Strings; e.g. if the String
was created by calling substring
on a larger String
. So when you zero the entire value
array you could be overwriting the state of other strings ... that don't contain passwords.
The cure is to only zero the part of the backing array that is used by the password string.
The JLS (17.5.3) warns that the effects of using reflection to change final
variables is undefined.
However, the context for this is the Java Memory Model, and the fact that the compiler is allowed to aggressively cache final
variables. In this case:
you would expect the String to be thread-confined, and
you shouldn't be using any of those variables again.
I wouldn't expect either of these to be real problems ... modulo fixing the over-aggressive zeroing of value
.
But the real concern is Velociraptors. :-)
I'm puzzled that you would actually bothering to zap passwords like this. When you think about it, what you are protecting against is the possibility that someone can read process memory ... or a core dump or swap file ... to retrieve passwords. But if someone can do that, your system security has to have already been compromised ... cos' those things most likely require root
access (or equivalent). And if they have root
access they can "debug" your program and catch the passwords before your application zaps them.
One argument I have against String is that it's just too easy to inadvertently make a copy. Using strings safely is possible in theory, but the whole library ecosystem is based on the assumption that it's perfectly OK to copy strings. In the end, considering all the restrictions, strings may not be as convenient for this use case as they generally are.