18

I just learned that a String is immutable. When I was reading the reason behind it a few reasons came up, for example performance increases, or since its value cannot be modified it can be shared by multiple threads. These reasons I do understand.

But I don't get how it is related to security. How does a String being immutable help in Java security?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Lolly
  • 34,250
  • 42
  • 115
  • 150
  • 3
    Where does it say that it helps for security? – ivant Mar 07 '13 at 15:24
  • example claim @ivant - https://www.journaldev.com/802/string-immutable-final-java quote => "2. If String is not immutable, then it would cause a severe security threat to the application. For example, database usernames and passwords are passed as String to get the database connection, in-socket programming host, and port details passed as String. Since String is immutable, it's value can’t be changed. Otherwise, any hacker could change the referenced value to cause security issues in the application." – nycynik Aug 29 '18 at 14:19
  • 2
    Thank you @nycynik. But I find this example highly contrived. If the attackers can gain such access that the only things "stopping" them is that they can't change these values, then your system has already been majorly hacked! They'll just _read_ the credentials and steal, modify or destroy your data directly in the DB. As far as I can tell, string immutability is orthogonal to the security. By itself It does not improve the security in any meaningful way. – ivant Aug 30 '18 at 06:32

3 Answers3

18

A very common practice in writing class libraries is storing the parameters passed into your API, say, in a constructor, like this:

public class MyApi {
    final String myUrl;
    public MyApi(String urlString) {
        // Verify that urlString points to an approved server
        if (!checkApprovedUrl(urlString)) throw new IllegalArgumentException();
        myUrl = urlString;
    }
}

Were String mutable, this would lead to a subtle exploit: an attacker would pass a good URL, wait for a few microseconds, and then set the URL to point to an attack site.

Since storing without copying is a reasonably common practice, and because strings are among the most commonly used data types, leaving strings mutable would open up many APIs that are not written yet open to a serious security problem. Making strings immutable closes this particular security hole for all APIs, including the ones that are not written yet.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • 2
    A good example of ("partial") mutability is `File`. Essentially it just wraps a `String`. However there have been a number of cases where it has been used for a security check. A malicious subclass can change betwixt check and use (TOCTOU/TOC2TOU vulnerability). – Tom Hawtin - tackline Mar 07 '13 at 17:17
  • 2
    I'm not sure how the subtle exploits are done but assuming the method would be intercepted somehow via another thread. Basically, because String is immutable if MyApi constructor is called with urlString "ABC", then the contents cannot be changed from outside the constructor. If it was not immutable, it could be mutated on the other thread simply by calling urlString = "someMaliciousUrl"; after the checkApprovedUrl call. Is that understanding correct? – Mercury Apr 30 '16 at 12:22
  • @Mercury Yes, this is correct understanding of the attack described above. – Sergey Kalinichenko Apr 30 '16 at 12:25
  • @Mercury Just one Edit in your comment I would like to add : as if reference is changed to refer another object ( using = ) then I guess it would have been not much concern and that is not string mutability. Its like `String urlRef = "goodurllink"; MyAPI api = MyApi(urlRef); urlRef.replace("goodurllink", "BadurlLink");` This would have happened if String class would have been mutable and invoking `replace` would have resulted in editing same string – nits.kk Feb 11 '19 at 16:02
4

Immutable strings are required for the SecurityManager concept to work. dasbklinkenlight is already on the right track with his answer, but mutable strings would break the sandbox concept entirely.

For example, when you do a new FileInputStream("foo"); to read a file, the API implementation will internally do among others:

  • invoke the security manager's checkRead method with "foo" as an argument and throw an exception if the check fails
  • use operating system calls to actually open the file if the security check passed

If the invoker is able to modify the string between these two steps, the security check may succeed for one file, while actually a different file will be opened.

jarnbjo
  • 33,923
  • 7
  • 70
  • 94
  • not sure If I understood correctly I have a doubt since java passes by Value security check happened for foo only foo will be opened – Sourabh Saldi Nov 25 '17 at 10:20
  • This doesn’t require immutable Strings, just that a copy is taken of the value before it is checked. Perhaps the immutability of Strings makes the implementation simpler, but it isn’t necessary. – tgdavies Jan 05 '21 at 07:49
0

String is immutable means that you cannot change the object itself, but you can change the reference of course. When you call(for example) a = "ty", you are actually changing the reference of a to a new object created by the String literal "ty". Changing an object means to use its methods to change one of its fields, for example:

Foo x = new Foo("the field");
x.setField("a new field");
System.out.println(x.getField()); // prints "a new field"

while in an immutable class (declared as final), for example String, you cannot change the current String but you can return a new String, i.e:

String s = "some text";
s.substring(0,4);
System.out.println(s); // still printing "some text"
String a = s.substring(0,4);
System.out.println(a); // prints "some"
topcat3
  • 2,561
  • 6
  • 33
  • 57
  • 5
    "final" doesn't mean it's immutable. For classes it means that you cannot inherit it. – ivant Mar 07 '13 at 15:25
  • to be immutable you have to be final so that your subclass doesn't break immutability – topcat3 Mar 07 '13 at 15:28
  • that may be the case, but it's not enough to declare it final to make it immutable. – ivant Mar 07 '13 at 15:29
  • 3
    I don't see where it was asked what "immutable" means or what final has to do with it. The question was why immutable strings are relevant to security. – jarnbjo Mar 07 '13 at 15:33