界: Code Quality

程式碼品質不佳,會導致無法預料的行為。從使用者的角度來看,這通常表現為可用性不佳。對於攻擊者而言,這提供了以意想不到的方式向系統施加壓力的機會。

Code Correctness: Constructor Invokes Overridable Function

Abstract
此類別的建構函式所呼叫的函數可被取代。
Explanation
當建構函式呼叫可取代的函數時,可能會在物件完全初始化之前,允許攻擊者存取 this 參考,這可進而導致弱點。

範例 1:以下呼叫可被取代的方法。


...
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;
}
}


由於 validateUser 函數和類別不是 final,這表示它們可以被取代,然後將變數初始化為會取代此函數的子類別時,會允許規避 validateUser 功能。例如:


...
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");
}
}
}
Example 1 中的程式碼會列印「Attack successful!」,因為 Attacker 類別會覆寫從 User 超級類別之建構函式呼叫的 validateUser() 函數,並且 Java 會先查看子類別中是否有從建構函式呼叫的函數。
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
[4] Standards Mapping - CIS Azure Kubernetes Service Benchmark 1
[5] Standards Mapping - CIS Amazon Elastic Kubernetes Service Benchmark 2
[6] Standards Mapping - CIS Amazon Web Services Foundations Benchmark 1
[7] Standards Mapping - CIS Google Kubernetes Engine Benchmark normal
desc.structural.java.code_correctness_constructor_invokes_overridable_function