|
| 1 | +/** |
| 2 | + * @id cpp/drivers/incorrect-usage-of-rtlcomparememory |
| 3 | + * @name Incorrect usage of RtlCompareMemory |
| 4 | + * @description `RtlCompareMemory` routine compares two blocks of memory and returns the number of bytes that match, not a boolean value indicating a full comparison like `RtlEqualMemory` does. |
| 5 | + * This query detects the return value of `RtlCompareMemory` being handled as a boolean. |
| 6 | + * @security.severity Important |
| 7 | + * @kind problem |
| 8 | + * @problem.severity error |
| 9 | + * @precision high |
| 10 | + * @tags security |
| 11 | + * kernel |
| 12 | + */ |
| 13 | + |
| 14 | +import cpp |
| 15 | + |
| 16 | +predicate isLiteralABooleanMacro(Literal l) { |
| 17 | + exists(MacroInvocation mi | mi.getExpr() = l | |
| 18 | + mi.getMacroName() in ["true", "false", "TRUE", "FALSE"] |
| 19 | + ) |
| 20 | +} |
| 21 | + |
| 22 | +from FunctionCall fc, Function f, Expr e, string msg |
| 23 | +where |
| 24 | + f.getQualifiedName() = "RtlCompareMemory" and |
| 25 | + f.getACallToThisFunction() = fc and |
| 26 | + ( |
| 27 | + exists(UnaryLogicalOperation ulo | e = ulo | |
| 28 | + ulo.getAnOperand() = fc and |
| 29 | + msg = "as an operand in an unary logical operation" |
| 30 | + ) |
| 31 | + or |
| 32 | + exists(BinaryLogicalOperation blo | e = blo | |
| 33 | + blo.getAnOperand() = fc and |
| 34 | + msg = "as an operand in a binary logical operation" |
| 35 | + ) |
| 36 | + or |
| 37 | + exists(Conversion conv | e = conv | |
| 38 | + ( |
| 39 | + conv.getType().hasName("bool") or |
| 40 | + conv.getType().hasName("BOOLEAN") or |
| 41 | + conv.getType().hasName("_Bool") |
| 42 | + ) and |
| 43 | + conv.getUnconverted() = fc and |
| 44 | + msg = "as a boolean" |
| 45 | + ) |
| 46 | + or |
| 47 | + exists(IfStmt s | e = s.getControllingExpr() | |
| 48 | + s.getControllingExpr() = fc and |
| 49 | + msg = "as the controlling expression in an If statement" |
| 50 | + ) |
| 51 | + or |
| 52 | + exists(EqualityOperation bao, Expr e2 | e = bao | |
| 53 | + bao.hasOperands(fc, e2) and |
| 54 | + isLiteralABooleanMacro(e2) and |
| 55 | + msg = |
| 56 | + "as an operand in an equality operation where the other operand is a boolean value (high precision result)" |
| 57 | + ) |
| 58 | + or |
| 59 | + exists(EqualityOperation bao, Expr e2 | e = bao | |
| 60 | + bao.hasOperands(fc, e2) and |
| 61 | + (e2.(Literal).getValue().toInt() = 1 or e2.(Literal).getValue().toInt() = 0) and |
| 62 | + not isLiteralABooleanMacro(e2) and |
| 63 | + msg = |
| 64 | + "as an operand in an equality operation where the other operand is likely a boolean value (lower precision result, needs to be reviewed)" |
| 65 | + ) |
| 66 | + ) |
| 67 | +select e, |
| 68 | + "This $@ is being handled $@ instead of the number of matching bytes. Please review the usage of this function and consider replacing it with `RtlEqualMemory`.", |
| 69 | + fc, "call to `RtlCompareMemory`", e, msg |
0 commit comments