Versions Compared

Key

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

...

Consider the following class definition. Unless someone knows the secret password, the value 1234 is a secretobjects cannot be created as the constructor for the class checks for the password stored in some password file.

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

    }
    
    public void use(){
     //
    }

    //...
}

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.
Bypassing the constructor leads to bypassing the password check done in the constructor.

Code Block
class Test extends MyPrivacy implements Cloneable{
    private int dummy;
    Test(int d) {
        dummy = d;
    }
    public static void mainsomefunction(String[]MyPrivacy argsobj) {
        Test t = new Test(0);
        Object obj = null;
	try {
            objTest t = t(Test)obj.clone();
        }catch(Exception e) {
            System.out.println("not cloneable");
        }
        if (objt != null)
            System.out.println(((MyPrivacy)obj).getKey());//steal keyt.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 {
    private//define intclass key = 1234;member fields
    //...
    
    public MyPrivacy(String passwd) {}
      public MyPrivacy(int k)String {actualPass;
        this.key = k;
    }
FileReader fr = new FileReader("Passfile.txt");
        BufferedReader br = new BufferedReader(fr);
        actualPass = br.readLine();
     protected  int getKeyif(actualPass.equals(passwd)){
            // return normally
        }
        else{
            // exit the program,  return this.key;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();
    }
}

...