用于数组构造的用户提供的大小验证不当¶
ID: java/improper-validation-of-array-construction
Kind: path-problem
Security severity: 8.8
Severity: warning
Precision: medium
Tags:
- security
- external/cwe/cwe-129
Query suites:
- java-security-extended.qls
- java-security-and-quality.qls
在指定新创建数组的大小时使用未验证的输入可能会导致创建大小为零的数组。如果随后在没有进一步检查的情况下访问此数组,则可能会抛出 ArrayIndexOutOfBoundsException
,因为无法保证数组不为空。
当用户输入在数组初始化期间用作大小时,无论直接使用还是经过一个或多个计算,都会发生此问题。如果用户输入未经验证,则可能会导致数组大小为零。
建议¶
在使用数组初始化中使用的尺寸之前,应验证其是否大于零。或者,可以通过条件检查来保护数组访问,以确保仅在索引小于数组大小时才访问数组。
示例¶
以下程序构造一个数组,其大小由某些用户输入指定
public class ImproperValidationOfArrayIndex extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
// User provided value
int numberOfItems = Integer.parseInt(request.getParameter("numberOfItems").trim());
if (numberOfItems >= 0) {
/*
* BAD numberOfItems may be zero, which would cause the array indexing operation to
* throw an ArrayIndexOutOfBoundsException
*/
String items = new String[numberOfItems];
items[0] = "Item 1";
}
if (numberOfItems > 0) {
/*
* GOOD numberOfItems must be greater than zero, so the indexing succeeds.
*/
String items = new String[numberOfItems];
items[0] = "Item 1";
}
} catch (NumberFormatException e) { }
}
}
第一个数组构造受检查用户输入是否为零或更多条件的保护。但是,如果用户提供 0
作为 numberOfItems
参数,则会创建一个空数组,并且任何数组访问都会因 ArrayIndexOutOfBoundsException
而失败。
第二个数组构造受检查用户输入是否大于零条件的保护。因此,数组永远不会为空,并且以下数组访问不会抛出 ArrayIndexOutOfBoundsException
。
参考¶
Java API 规范:ArrayIndexOutOfBoundsException。
通用弱点枚举:CWE-129。