11/**
22 * @name Integer addition may overflow inside if statement
3- * @description Detects "if (a+b>c) a=c-b", which incorrectly implements
4- * a = min(a,c-b) if a+b overflows. Should be replaced by
5- * "if (a>c-b) a=c-b". Also detects "if (b+a>c) a=c-b"
6- * (swapped terms in addition), if (a+b>c) { a=c-b }"
7- * (assignment inside block), "c<a+b" (swapped operands) and
8- * ">=", "<", "<=" instead of ">" (all operators). This
9- * integer overflow is the root cause of the buffer overflow
10- * in the SHA-3 reference implementation (CVE-2022-37454).
3+ * @description "if (a+b>c) a=c-b" was detected where "a+b" may potentially
4+ * produce an integer overflow (or wraparound). The code can be
5+ * rewritten to "if (a>c-b) a=c-b" which avoids the overflow.
116 * @kind problem
127 * @problem.severity warning
138 * @id cpp/if-statement-addition-overflow
@@ -27,7 +22,6 @@ from IfStmt ifstmt, RelationalOperation relop, ExprStmt exprstmt, BlockStmt bloc
2722where ifstmt .getCondition ( ) = relop and
2823 relop .getAnOperand ( ) = addexpr and
2924 addexpr .getUnspecifiedType ( ) instanceof IntegralType and
30- subexpr .getUnspecifiedType ( ) instanceof IntegralType and
3125 not isFromMacroDefinition ( relop ) and
3226 exprMightOverflowPositively ( addexpr ) and
3327 ( ifstmt .getThen ( ) = exprstmt or
@@ -39,6 +33,5 @@ where ifstmt.getCondition() = relop and
3933 globalValueNumber ( addexpr .getRightOperand ( ) ) = globalValueNumber ( subexpr .getRightOperand ( ) ) ) or
4034 ( hashCons ( addexpr .getRightOperand ( ) ) = hashCons ( assignexpr .getLValue ( ) ) and
4135 globalValueNumber ( addexpr .getLeftOperand ( ) ) = globalValueNumber ( subexpr .getRightOperand ( ) ) ) ) and
42- globalValueNumber ( relop .getAnOperand ( ) ) = globalValueNumber ( subexpr .getLeftOperand ( ) ) and
43- not globalValueNumber ( addexpr .getAnOperand ( ) ) = globalValueNumber ( relop .getAnOperand ( ) )
36+ globalValueNumber ( relop .getAnOperand ( ) ) = globalValueNumber ( subexpr .getLeftOperand ( ) )
4437select ifstmt , "Integer addition may overflow inside if statement."
0 commit comments