Kingdom: Code Quality

Poor code quality leads to unpredictable behavior. From a user's perspective that often manifests itself as poor usability. For an attacker it provides an opportunity to stress the system in unexpected ways.

Code Correctness: Constructor Invokes Overridable Function

Abstract
A constructor of the class calls a function that can be overridden.
Explanation
When a constructor calls an overridable function, it may allow an attacker to access the this reference prior to the object being fully initialized, which can in turn lead to a vulnerability.

Example 1: The following calls a method that can be overridden.


...
class User {
private String username;
private boolean valid;
public User(String username, String password){
this.username = username;
this.valid = validateUser(username, password);
}
public boolean validateUser(String username, String password){
//validate user is real and can authenticate
...
}
public final boolean isValid(){
return valid;
}
}


Since the function validateUser and the class are not final, it means that they can be overridden, and then initializing a variable to the subclass that overrides this function would allow bypassing of the validateUser functionality. For example:


...
class Attacker extends User{
public Attacker(String username, String password){
super(username, password);
}
public boolean validateUser(String username, String password){
return true;
}
}
...
class MainClass{
public static void main(String[] args){
User hacker = new Attacker("Evil", "Hacker");
if (hacker.isValid()){
System.out.println("Attack successful!");
}else{
System.out.println("Attack failed");
}
}
}


The code in Example 1 prints "Attack successful!", since the Attacker class overrides the validateUser() function that is called from the constructor of the superclass User, and Java will first look in the subclass for functions called from the constructor.
References
[1] MET05-J. Ensure that constructors do not call overridable methods CERT
[2] EXTEND-5: Limit the extensibility of classes and methods Oracle
[3] OBJECT-4: Prevent constructors from calling methods that can be overridden Oracle
desc.structural.java.code_correctness_constructor_invokes_overridable_function