DAGDA SEARCH | Back to results | Support

User-controlled data in arithmetic expression — CodeQL query help documentation

Source: https://codeql.github.com/codeql-query-help/java/java-tainted-arithmetic/

User-controlled data in arithmetic expression

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

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:

Example

In this example, a value is read from standard input into an int. 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.

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;
		}
	}
}

References