算术表达式中的用户控制的数据¶
ID: java/tainted-arithmetic
Kind: path-problem
Security severity: 8.6
Severity: warning
Precision: medium
Tags:
- security
- external/cwe/cwe-190
- external/cwe/cwe-191
Query suites:
- java-security-extended.qls
- java-security-and-quality.qls
对用户控制的数据执行计算会导致整数溢出,除非验证输入。
如果用户可以自由输入非常大的数字,即使通常会导致幅度发生很小变化的算术运算也可能导致溢出。
建议¶
始终通过执行以下操作之一来防止用户控制的数据在算术运算中的溢出
验证用户输入。
对算术表达式定义一个保护,以便仅在结果可以确定小于或等于类型的最大值(例如
MAX_VALUE
)时才执行运算。使用更宽的类型,以便较大的输入值不会导致溢出。
示例¶
在此示例中,从标准输入读取一个值到 int
中。由于该值是用户控制的值,因此它可能非常大。因此,对该值执行算术运算可能会导致溢出。为了避免这种情况,示例显示了如何在执行乘法之前执行检查。
class Test {
public static void main(String[] args) {
{
int data;
BufferedReader readerBuffered = new BufferedReader(
new InputStreamReader(System.in, "UTF-8"));
String stringNumber = readerBuffered.readLine();
if (stringNumber != null) {
data = Integer.parseInt(stringNumber.trim());
} else {
data = 0;
}
// BAD: may overflow if input data is very large, for example
// 'Integer.MAX_VALUE'
int scaled = data * 10;
//...
// GOOD: use a guard to ensure no overflows occur
int scaled2;
if (data < Integer.MAX_VALUE / 10)
scaled2 = data * 10;
else
scaled2 = Integer.MAX_VALUE;
}
}
}
参考资料¶
SEI CERT Oracle Java 编码标准:NUM00-J. 检测或防止整数溢出.
常见弱点枚举:CWE-190.
常见弱点枚举:CWE-191.