Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

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. Unless someone knows the secret password, objects cannot be created as the constructor for the class checks for the password stored in some password file.

...

Code Block
class Test extends MyPrivacy implements Cloneable{
    
    public static void somefunction(MyPrivacy obj) {
        
	try {
            Test t = (Test)obj.clone()
        }catch(Exception e) {
            System.out.println("not cloneable");
        }
        if (t != null)
            t.use(); // Another object instantiated without knowing the password.....
    }
}


 Compliant Solution 1

Classes should be made non cloneable to prevent this from occuring. The following method maybe implemented for achieving this.

Code Block
class MyPrivacy {
    //define class member fields
    //...
    
    public MyPrivacy(String passwd) {
        String actualPass;
        FileReader fr = new FileReader("Passfile.txt");
        BufferedReader br = new BufferedReader(fr);
        actualPass = br.readLine();
        if(actualPass.equals(passwd)){
            // return normally
        }
        else{
            // exit the program, print an authentication error 
            // preventing the class object from being created
        }

    }
    
    public void use(){
     //
    }

    //...
    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.

...