Versions Compared

Key

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

...

Code Block
bgColor#ffcccc
class SensitiveClass {
  private char[] filename;
  private Boolean shared = false;
 
  protected SensitiveClass(String filename) {
    this.filename = filename.toCharArray();
  }

  protected void replace(){
    if(!shared)
      for(int i = 0;i<filename i < filename.length; i++) {
    	filename[i]= 'x';
    }
  }

  protected String get(){
    if(!shared){	
      shared = true;
      return String.valueOf(filename);
    } else {
      throw new Error("Error getting instance");
    }
  }
  
  protected void printFilename(){
    System.out.println(String.valueOf(filename));
  }
}

class MaliciousSubclass extends SensitiveClass implements Cloneable {	
  protected MaliciousSubclass(String filename) {
    super(filename);
  }
  
  @Override public MaliciousSubclass clone() {  // Well-behaved clone() method
    MaliciousSubclass s = null;
    try {
      s = (MaliciousSubclass)super.clone();	        
    } catch(Exception e) { 
      System.out.println("not cloneable"); 
    }
    return s;
  }

  public static void main(String[] args){
    MaliciousSubclass ms1 = new MaliciousSubclass("file.txt");
    MaliciousSubclass ms2 = ms1.clone(); // Creates a copy 
    String s = ms1.get();  // Returns filename
    System.out.println(s); // Filename is "file.txt"
    ms2.replace();         // Replaces all characters with x'
    // Both ms1.get() and ms2.get() will subsequently return filename = 'xxxxxxxx'
    ms1.printFilename();   // Filename becomes 'xxxxxxxx' 
    ms2.printFilename();   // Filename becomes 'xxxxxxxx'
  }
}

...