界: Code Quality

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

Code Correctness: Comparison of Boxed Primitive Types

Abstract
使用相等運算子 (而不是 equals() 方法) 比較方塊化原始物件,可導致非預期的行為。
Explanation
在處理方塊化原始物件並進行相等比較時,應該呼叫方塊化原始物件的 equals() 方法,而不是 ==!= 運算子。Java 規格載明有關方塊化轉換的資訊:

"如果將要方塊化的值 p 是類型為 int 並且是 -128 到 127 (含) 之間的整數常值,或為 true 或 false 的 Boolean 常值,或是「\u0000」到「\u007f」(含) 之間的字元常值,則會使 a 和 b 成為 p 之任何兩個方塊化轉換的結果。永遠會是 a == b 的情況。"

這表示,如果使用方塊化原始物件 (而不是 BooleanByte),則只會快取或記住某個範圍的值。對於值子集,使用 ==!= 將會傳回正確的值,對於此子集之外的所有其他值,這會傳回物件位址的比較結果。

範例 1:以下範例對方塊化原始物件使用相等運算子。


...
Integer mask0 = 100;
Integer mask1 = 100;
...
if (file0.readWriteAllPerms){
mask0 = 777;
}
if (file1.readWriteAllPerms){
mask1 = 777;
}
...
if (mask0 == mask1){
//assume file0 and file1 have same permissions
...
}
...
Example 1 中的程式碼使用 Integer 方塊化原始物件,來嘗試比較兩個 int 值。如果 mask0mask1 同時等於 100,則 mask0 == mask1 將會傳回 true。但是,現在當 mask0mask1 都等於 777 時,mask0 == maske1 將會傳回 false,因為這些值不在這些方塊化原始物件的快取值範圍內。
References
[1] EXP03-J. Do not use the equality operators when comparing values of boxed primitives CERT
[2] Java Language Specification Chapter 5. Conversions and Contexts Oracle
[3] Standards Mapping - CIS Azure Kubernetes Service Benchmark 1.0
[4] Standards Mapping - CIS Amazon Elastic Kubernetes Service Benchmark 5.0
[5] Standards Mapping - CIS Amazon Web Services Foundations Benchmark 1
[6] Standards Mapping - CIS Google Kubernetes Engine Benchmark normal
[7] Standards Mapping - Common Weakness Enumeration CWE ID 398, CWE ID 754
[8] Standards Mapping - OWASP Application Security Verification Standard 4.0 11.1.7 Business Logic Security Requirements (L2 L3)
[9] Standards Mapping - SANS Top 25 2010 Risky Resource Management - CWE ID 754
desc.structural.java.code_correctness_comparison_of_boxed_primitive_types