不受控分配大小溢出¶
ID: cpp/uncontrolled-allocation-size
Kind: path-problem
Security severity: 8.1
Severity: error
Precision: medium
Tags:
- reliability
- security
- external/cwe/cwe-190
- external/cwe/cwe-789
Query suites:
- cpp-security-extended.qls
- cpp-security-and-quality.qls
此代码通过将用户输入乘以 sizeof
表达式来计算分配大小。由于用户输入没有明显的幅度保护,因此此乘法可能会溢出。当整数乘法在 C 中溢出时,结果可能会环绕并远小于预期。之后尝试将数据放入分配的缓冲区可能会导致溢出。
建议¶
保护来自外部用户的全部整数参数。使用参数的预期范围实现保护,并确保输入值满足此范围的最小值和最大值要求。如果输入值未通过此保护,则在继续执行之前拒绝请求。如果输入值通过了保护,则后续计算不应溢出。
示例¶
int factor = atoi(getenv("BRANCHING_FACTOR"));
// GOOD: Prevent overflow by checking the input
if (factor < 0 || factor > 1000) {
log("Factor out of range (%d)\n", factor);
return -1;
}
// This line can allocate too little memory if factor
// is very large.
char **root_node = (char **) malloc(factor * sizeof(char *));
此代码展示了一种保护输入值在预期范围内的示例方法。如果 factor
未通过保护,则会返回错误,并且该值不会用作后续对 malloc
的调用的参数。如果没有此保护,则分配的缓冲区可能太小,无法容纳为其准备的数据。
参考¶
CERT Oracle 针对 C 的安全编码标准:INT04-C. 对来自受污染源的整数值的限制进行强制执行.
通用弱点枚举:CWE-190.
通用弱点枚举:CWE-789.