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.
Compliant Code
Non Compliant Code
Consider the following class definition, the value 1234 is a secret.
Code Block |
---|
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.
Code Block |
---|
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 classes should be made non cloneable to prevent this from occuring. The following method maybe implemented for achieving this.
Code Block |
---|
 public 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.
Code Block |
---|
 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.
...