SV.TAINTED.BINOPUse of Unvalidated Integers in Binary OperationsWhenever input data is accepted from the user or the outside environment, it should be validated for type, length, format, and range before it is used. Until this data is properly validated, it is said to be tainted. The SV.TAINTED family of checkers looks for the use of tainted data in code. The SV.TAINTED.BINOP checker flags code that uses tainted data in arithmetic binary operations, such as addition, subtraction, or multiplication. Vulnerability and riskWhen integer data input to the code is not validated properly and is used as an operand to a binary operation, the result can be an integer overflow or wraparound. This potential situation could allow an attacker to alter the normal control flow, causing an unexpected program behavior. In the worst-case scenarios, an attacker could:
Mitigation and preventionTo avoid tainted input errors:
Vulnerable code example1 int get_altitude(); 2 void set_altitude(int); 3 4 int get_untrusted() { 5 int i; 6 scanf("%d", &i); 7 return i; 8 } 9 10 extern const int max_altitude; 11 12 void increase_altitude() { 13 int current_altitude = get_altitude(); 14 int shift = get_untrusted(); 15 if (shift > 0) { 16 int new_altitude = current_altitude + shift; 17 if (new_altitude < max_altitude) { 18 set_altitude(new_altitude); 19 } 20 } 21 } In the above example, an attacker can provide an arbitrarily large value for variable 'new_altitude'. If the binary operation at line 16 overflows, this can result in a negative value of variable 'new_altitude', and cause unexpected program behavior. Klocwork reports an SV.TAINTED.BINOP defect at line 11, indicating: "Unvalidated integer value 'shift' that is received from 'get_untrusted' at line 14 is used as an operand to a binary operator at line 16". Fixed code example1 int get_altitude(); 2 void set_altitude(int); 3 4 int get_untrusted() { 5 int i; 6 scanf("%d", &i); 7 return i; 8 } 9 10 extern const int max_altitude; 11 extern const int max_trusted_shift; 12 13 void increase_altitude() { 14 int current_altitude = get_altitude(); 15 int shift = get_untrusted(); 16 if (shift > 0 && shift < max_trusted_shift) { 17 int new_altitude = current_altitude + shift; 18 if (new_altitude < max_altitude) { 19 set_altitude(new_altitude); 20 } 21 } 22 } The Klocwork checker no longer produces the defect report here, since the integer value 'shift' is validated at line 16 before being used in the binary operation. Related checkersExternal guidance |