How does string immutability improve security?

Viewed 158

It is common to hear that strings are immutable and this improves security. I understand the idea that since strings are final, their contents cannot be changed later. But even if the content could be changed, i think it is still safe as the code is written by developer instead of attacker. Or else in practice, how does this attack are being done actually?

I saw an example online that indicated an attacker could bypass security if strings were mutable. I don't get it. The below code is written by service provider. This is the part attacker can never touch. Whether strings are mutable or not attackers can never modify their values, right?

public class FileInputStream
{
 private String filename;
 public FileInputStream(String filename)
 {
  if (!allowedToReadFile(filename))
  throw new SecurityException();
  this.filename = filename;
  }
  ...
 }
1 Answers

Consider Strings are mutable. In the constructor the the filename gets checked and a reference to the string is stored in the object. There might be another method that opens the file using that filename. If the contents of the string were modified to another filename before calling that method, then the method opens the new file without failing the allowedToReadFile check, which would have happened when the String with the new contents was passed at the start. In this case the attacker has access to almost any file by bypassing the check and changing the contents of the string later.

In general making data immutable can avoid many security problems an other problems. If Strings were mutable in Java, it wouldn't prevent you from changing the contents of the string from another thread. You might even notice that the string changed during a function call. Printing half of the old string and half of the new string to the screen. It might even mess with Unicode encoding. An other question to ask would be, what happens with literals, when you change them? Waste memory and create a new instance of the string represented by the literal? Or create only one String for one literal. If Strings were mutable, there should have been an other system to copy objects, maybe a system like in C++, in which Strings are indeed mutable. Assigning Strings copies them. But this comes at a cost: Copying or the need of a new complex language feature tha allows moving, borrowing, and const reference passing to functions. The JVM is not designed for those features.

Related