...
Code Block |
---|
public class Interceptor extends BankOperations { private static Interceptor stealInstance = null; public static Interceptor get() { try { new Interceptor(); } catch(Exception ex) { } // ignore the exception try { synchronized(Interceptor.class) { while (stealInstance == null) { System.gc(); Interceptor.class.wait(10); } } } catch(InterruptedException ex) { return null; } return stealInstance; } public void finalize() { synchronized(Interceptor.class) { stealInstance = this; Interceptor.class.notify(); } System.out.println("Stolen the instance in finalize of " + this); } } public class AttackerApp { //invoke Invoke class and gain access to the restrictive features public static void main(String[] args) { Interceptor i = Interceptor.get(); Storage.store(i); // Can store the stolen object i.greet(); //now Now invoke any method of BankOperations class UserApp.main(args); // Invoke the original UserApp } } |
This code is an exception to OBJ02-J. Avoid using finalizers
Compliant Solution
One compliant solution is to use an initialization flag that is explicitly set after the constructor has finished initializing the class. This flag should be tested before code is executed in any method. This (rather) imposing solution is recommended for security sensitive applications. For others, it is reasonable to initialize the default values of class variables to something like null
. \Check this
Code Block | ||
---|---|---|
| ||
public class BankOperations {
public volatile boolean initialized = false;
public BankOperations() {
if (!performSSNVerification()) {
throw new SecurityException("Invalid SSN!");
}
else
initialized = true;
}
private boolean performSSNVerification() {
return false;
}
public void greet() {
if(initialized == true) {
System.out.println("Welcome user! You may now use all the features.");
//other authorized code
}
else
System.out.println("You are not permitted!");
}
}
|
Compliant Solution
Another compliant solution is to declare the The compliant solution declares the partially-initialized class final so that it cannot be extended.
Code Block | ||
---|---|---|
| ||
public final class BankOperations { ... |
...