...
Non Compliant code example:
...
Code Block |
---|
public class NonFinal{
  //sole constructor
  String ssn= new String("123456");
  public NonFinal() {
  //invoke java.lang.Object.getClass to get class instance
  Class clazz = getClass();
   Method m = clazz.getMethod(ssn, (Class[])null); Â
    m.invoke(this, (Object[])null) ;
   }
  public void getSSN() {
    System.out.println("The SSN is: " + ssn);
  }
}
Â
public class subClass extends NonFinal {
  public subClass() {
    NonFinal();
  }
   public void getSSN() {
      ssn = "456789";
      System.out.println("The SSN is: "+ssn);
  }
  public void main(String[] args) {
    subClass subclass = new subClass();
   }
}
|
Here, an attacker can easily create an instance and override methods of the NonFinal class.
...
The compliant solution confirms the object's class type by examining the java.lang.Class instance belonging to that object since the instances are scoped by the class name and the class loader that defined the class.
Code Block |
---|
public class NonFinal{
//sole constructor
String ssn = new String("123456");
public NonFinal() {
//invoke java.lang.Object.getClass to get class instance
Class clazz = getClass();
//confirm class type
if (clazz != NonFinal.class) {
 //permission needed to subclass NonFinal
securityManagerCheck();
}
m.invoke(this, (Object[])null) ;
Method m = clazz.getMethod(ssn, (Class[])null);
m.invoke(this, (Object[])null);
}
 public void getSSN() {
System.out.println("The SSN is: " + ssn);
}
private void securityManagerCheck() {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
       sm.checkPermission(Permission perm, sm.getSecurityContext());
}
}
}
Â
public class subClass extends NonFinal {
public subClass() {
NonFinal();
}
public void getSSN() {
ssn = "456789";
System.out.println("The SSN is: "+ssn);
}
public void main(String[] args) {
subClass subclass = new subClass();
}
}
|
Risk Assessment:
Allowing a non-final class or method to be inherited without checking the class instances, allows an attacker to exploit it.
...