User-controlled data in arithmetic expression¶
ID: java/tainted-arithmeticKind: path-problemSecurity severity: 8.6Severity: warningPrecision: mediumTags: - security - external/cwe/cwe-190 - external/cwe/cwe-191Query suites: - java-security-extended.qls - java-security-and-quality.qls
Click to see the query in the CodeQL repository
Performing calculations on user-controlled data can result in integer overflows unless the input is validated.
If the user is free to enter very large numbers, even arithmetic operations that would usually result in a small change in magnitude may result in overflows.
Recommendation¶
Always guard against overflow in arithmetic operations on user-controlled data by doing one of the following:
Validate the user input.
Define a guard on the arithmetic expression, so that the operation is performed only if the result can be known to be less than, or equal to, the maximum value for the type, for example
MAX_VALUE.Use a wider type, so that larger input values do not cause overflow.
Example¶
In this example, a value is read from standard input into anint. Because the value is a user-controlled value, it could be extremely large. Performing arithmetic operations on this value could therefore cause an overflow. To avoid this happening, the example shows how to perform a check before performing a multiplication.
classTest{publicstaticvoidmain(String[]args){{intdata;BufferedReaderreaderBuffered=newBufferedReader(newInputStreamReader(System.in,"UTF-8"));StringstringNumber=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'intscaled=data*10;//...// GOOD: use a guard to ensure no overflows occurintscaled2;if(data<Integer.MAX_VALUE/10)scaled2=data*10;elsescaled2=Integer.MAX_VALUE;}}}
References¶
SEI CERT Oracle Coding Standard for Java:NUM00-J. Detect or prevent integer overflow.
Common Weakness Enumeration:CWE-190.
Common Weakness Enumeration:CWE-191.