未正确验证用户提供的数组索引¶
ID: java/improper-validation-of-array-index
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
。这是因为无法保证提供的索引在数组的边界内。
当用户输入直接或在进行一次或多次计算后用作数组索引时,会出现此问题。如果用户输入未经清理,则它可以是任何值,这可能导致负索引或大于数组大小的索引,这两者都会导致 ArrayIndexOutOfBoundsException
。
建议¶
在使用数组访问中使用的索引应在使用前根据数组的边界进行检查。索引应小于数组大小,且不应为负数。
示例¶
以下程序从固定大小常量数组中访问一个元素
public class ImproperValidationOfArrayIndex extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String[] productDescriptions = new String[] { "Chocolate bar", "Fizzy drink" };
// User provided value
String productID = request.getParameter("productID");
try {
int productID = Integer.parseInt(userProperty.trim());
/*
* BAD Array is accessed without checking if the user provided value is out of
* bounds.
*/
String productDescription = productDescriptions[productID];
if (productID >= 0 && productID < productDescriptions.length) {
// GOOD We have checked that the array index is valid first
productDescription = productDescriptions[productID];
} else {
productDescription = "No product for that ID";
}
response.getWriter().write(productDescription);
} catch (NumberFormatException e) { }
}
}
对 productDescriptions
数组的第一次访问将用户提供的值用作索引,而未执行任何检查。如果用户提供负值或大于数组大小的值,则可能会抛出 ArrayIndexOutOfBoundsException
。
对 productDescriptions
数组的第二次访问包含在条件表达式中,该表达式验证用户提供的值是数组中的有效索引。这可确保访问操作绝不会抛出 ArrayIndexOutOfBoundsException
。
参考¶
Java API 规范:ArrayIndexOutOfBoundsException。
常见弱点枚举:CWE-129。