Re: Why is String immutable?
The second reason has to do with the Java security model. When a
security policy is installed, certain restrictions can be enforced on --
for example -- which files can be read, which hosts can be connected to
over the network, and so on. The immutable String class ensures that
security-sensitive APIs only have to check the file name or host name
once, and can then rely on it to stay the same. A mutable String class
would introduce a race condition where the application (in another
thread) could modify the file name after the security check, but before
the file is actually opened, and thus circumvent the security mechanism.
Hi, I wholeheartedly agree with your first point of it being the only
sane way to implement Strings from a design point of view, but I'm less
sure about relying on this for security. The underlying char[] is still
writable if you try a bit harder. I expect the method below could be
forbidden with the right security policy (ReflectPermission
seems to be granted by default on my system) but I suspect you could
still access the field directly if you craft your own byte code?
import java.lang.reflect.Field;
public class StringImmutabilityTest {
public static void main(String[] args) throws Exception {
String fileNameToServe = "/ftp/readme";
char[] injection = "/etc/passwd".toCharArray();
Field f = fileNameToServe.getClass().getDeclaredField("value");
f.setAccessible(true);
char[] val = (char[]) f.get(fileNameToServe);
System.arraycopy(injection, 0, val, 0, injection.length);
System.out.println(fileNameToServe);
}
}
Of course, you're probably doomed the moment you allow untrusted code
into your VM anyway!
By the way, calling new String(String) on any untrusted Strings will
probably keep you a little safe from this.
Matt