Wave Wave - 8 months ago 31
Java Question

How does Java string being immutable increase security?

I am new to Java and when learning, I came across the fact that a

is immutable. When I was reading the reason behind it, a few reasons came up, for example performance increasements, since its value cannot be modified, and 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
being immutable help in Java security?

Please help me in understanding. Thanks in advance.


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.