Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Why shouldn't clone() be used for defensive copying?

In Effective Java (Chapter 7), it says

Note also that we did not use Date’s clone method to make the defensive copies. Because Date is nonfinal, the clone method is not guaranteed to return an object whose class is java.util.Date: it could return an instance of an untrusted subclass specifically designed for malicious mischief. Such a subclass could, for example, record a reference to each instance in a private static list at the time of its creation and allow the attacker to access this list. This would give the attacker free reign over all instances. To prevent this sort of attack, do not use the clone method to make a defensive copy of a parameter whose type is subclassable by untrusted parties.

I don't quite understand its explanation. Why does clone() not return a Date object? How can the instance be of untrusted subclass?

like image 937
Kyle Avatar asked Apr 09 '15 02:04

Kyle


2 Answers

Consider this code:

public class MaliciousDate extends Date { /** malicious code here **/ }

public class SomeClass {
    public static void main(String[] args) {
        MaliciousDate someDate = new MaliciousDate();
        Date copyOfMaliciousDate = someDate;
        Date anotherDate = copyOfMaliciousDate.clone();
    }
}

Since copyOfMaliciousDate is of type Date, you can call clone() and it will return a Date object, but calling clone on copyOfMaliciousDate executes the code written in the MaliciousDate class' clone() because the instance stored in copyOfMaliciousDate is a MaliciousDate.

like image 179
egracer Avatar answered Sep 19 '22 12:09

egracer


clone() is widely regarded to have been a failed experiment for a number of reasons. In this case, someone passing in a Date could have passed in an EvilDate extends Date whose clone() method sneakily returned a copy that was still mutable by someone else.

like image 23
chrylis -cautiouslyoptimistic- Avatar answered Sep 18 '22 12:09

chrylis -cautiouslyoptimistic-