Java's Object cloning mechanism can allow an attacker to manufacture new instances of classes that have been defined, without executing its constructor. If a class is not cloneable, the attacker can define a subclass, and make the subclass implement the java.lang.Cloneable interface. This lets an attacker create new instances of the class. The new instances of the class are made by copying the memory images of existing objects; though this is sometimes an acceptable way of making a new object, it often is not.
Non Compliant Code
Consider the following class definition, the value 1234 is a secret.
class MyPrivacy { private int key = 1234; //... public MyPrivacy() {} public MyPrivacy(int k) { this.key = k; } protected int getKey() { return this.key; } //... }
The attacker can create a new instance of MyPrivacy class by using a cloneable subclass and by-pass the constructor and leave the field not initialized or even steal data. This can be showed by the following code.
class Test extends MyPrivacy implements Cloneable{ private int dummy; Test(int d) { dummy = d; } public static void main(String[] args) { Test t = new Test(0); Object obj = null; try { obj = t.clone(); }catch(Exception e) { System.out.println("not cloneable"); } if (obj != null) System.out.println(((MyPrivacy)obj).getKey());//steal key } }
Compliant Solution 1
Classes should be made non cloneable to prevent this from occuring. The following method maybe implemented for achieving this.
class MyPrivacy { private int key = 1234; //... public MyPrivacy() {} public MyPrivacy(int k) { this.key = k; } protected int getKey() { return this.key; } //... public final void clone() throws java.lang.CloneNotSupportedException{ throw new java.lang.CloneNotSupportedException(); } }
Compliant Solution 2
One can also make a class non subclassable. This can be achieved by finalizing a class.
 final class MyPrivacy { // Rest of the definition remains the same }
If, it is absolutely required to make the class cloneable, even then protective measures can be taken.
#1. If clone method is being over-riden, make it final
#2. If the class is reliant on a non-final clone method of one of the superclasses, then define the following
public final void clone() throws java.lang.CloneNotSupportedException { super.clone(); }