Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Java strings being immutable increase security?

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?

like image 271
Lolly Avatar asked Mar 07 '13 15:03

Lolly


People also ask

What are the benefits of strings being immutable Java?

Why Is String Immutable in Java? The key benefits of keeping this class as immutable are caching, security, synchronization, and performance.

Why string is secure in Java?

Strings Are Immutable Strings in Java are immutable which means that we cannot change them using any high-level APIs. Any change on a String object will produce a new String, keeping the old one in memory. Therefore, the password stored in a String will be available in memory until Garbage Collector clears it.

What is the advantage of having immutable objects?

Improved safety - Once you've verified the state of an immutable object, you can be confident that it will stay safe and valid (no background process will be able to change it without you knowing) Better caching - You can cache references to immutable objects since they won't change.

Why do we need immutability in Java?

An immutable class is good for caching purposes because you don't have to worry about the value changes. An immutable class is inherently thread-safe, so you don't have to worry about thread safety in multi-threaded environments.


1 Answers

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.

like image 190
Sergey Kalinichenko Avatar answered Oct 04 '22 00:10

Sergey Kalinichenko