/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/StaticAnalyzer/Checkers/MallocOverflowSecurityChecker.cpp
Line | Count | Source (jump to first uncovered line) |
1 | | // MallocOverflowSecurityChecker.cpp - Check for malloc overflows -*- C++ -*-=// |
2 | | // |
3 | | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | | // See https://llvm.org/LICENSE.txt for license information. |
5 | | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | | // |
7 | | //===----------------------------------------------------------------------===// |
8 | | // |
9 | | // This checker detects a common memory allocation security flaw. |
10 | | // Suppose 'unsigned int n' comes from an untrusted source. If the |
11 | | // code looks like 'malloc (n * 4)', and an attacker can make 'n' be |
12 | | // say MAX_UINT/4+2, then instead of allocating the correct 'n' 4-byte |
13 | | // elements, this will actually allocate only two because of overflow. |
14 | | // Then when the rest of the program attempts to store values past the |
15 | | // second element, these values will actually overwrite other items in |
16 | | // the heap, probably allowing the attacker to execute arbitrary code. |
17 | | // |
18 | | //===----------------------------------------------------------------------===// |
19 | | |
20 | | #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h" |
21 | | #include "clang/AST/EvaluatedExprVisitor.h" |
22 | | #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h" |
23 | | #include "clang/StaticAnalyzer/Core/Checker.h" |
24 | | #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h" |
25 | | #include "llvm/ADT/APSInt.h" |
26 | | #include "llvm/ADT/SmallVector.h" |
27 | | #include <optional> |
28 | | #include <utility> |
29 | | |
30 | | using namespace clang; |
31 | | using namespace ento; |
32 | | using llvm::APSInt; |
33 | | |
34 | | namespace { |
35 | | struct MallocOverflowCheck { |
36 | | const CallExpr *call; |
37 | | const BinaryOperator *mulop; |
38 | | const Expr *variable; |
39 | | APSInt maxVal; |
40 | | |
41 | | MallocOverflowCheck(const CallExpr *call, const BinaryOperator *m, |
42 | | const Expr *v, APSInt val) |
43 | 22 | : call(call), mulop(m), variable(v), maxVal(std::move(val)) {} |
44 | | }; |
45 | | |
46 | | class MallocOverflowSecurityChecker : public Checker<check::ASTCodeBody> { |
47 | | public: |
48 | | void checkASTCodeBody(const Decl *D, AnalysisManager &mgr, |
49 | | BugReporter &BR) const; |
50 | | |
51 | | void CheckMallocArgument( |
52 | | SmallVectorImpl<MallocOverflowCheck> &PossibleMallocOverflows, |
53 | | const CallExpr *TheCall, ASTContext &Context) const; |
54 | | |
55 | | void OutputPossibleOverflows( |
56 | | SmallVectorImpl<MallocOverflowCheck> &PossibleMallocOverflows, |
57 | | const Decl *D, BugReporter &BR, AnalysisManager &mgr) const; |
58 | | |
59 | | }; |
60 | | } // end anonymous namespace |
61 | | |
62 | | // Return true for computations which evaluate to zero: e.g., mult by 0. |
63 | 28 | static inline bool EvaluatesToZero(APSInt &Val, BinaryOperatorKind op) { |
64 | 28 | return (op == BO_Mul) && (Val == 0)27 ; |
65 | 28 | } |
66 | | |
67 | | void MallocOverflowSecurityChecker::CheckMallocArgument( |
68 | | SmallVectorImpl<MallocOverflowCheck> &PossibleMallocOverflows, |
69 | 25 | const CallExpr *TheCall, ASTContext &Context) const { |
70 | | |
71 | | /* Look for a linear combination with a single variable, and at least |
72 | | one multiplication. |
73 | | Reject anything that applies to the variable: an explicit cast, |
74 | | conditional expression, an operation that could reduce the range |
75 | | of the result, or anything too complicated :-). */ |
76 | 25 | const Expr *e = TheCall->getArg(0); |
77 | 25 | const BinaryOperator * mulop = nullptr; |
78 | 25 | APSInt maxVal; |
79 | | |
80 | 51 | for (;;) { |
81 | 51 | maxVal = 0; |
82 | 51 | e = e->IgnoreParenImpCasts(); |
83 | 51 | if (const BinaryOperator *binop = dyn_cast<BinaryOperator>(e)) { |
84 | 28 | BinaryOperatorKind opc = binop->getOpcode(); |
85 | | // TODO: ignore multiplications by 1, reject if multiplied by 0. |
86 | 28 | if (mulop == nullptr && opc == BO_Mul25 ) |
87 | 25 | mulop = binop; |
88 | 28 | if (opc != BO_Mul && opc != BO_Add1 && opc != BO_Sub0 && opc != BO_Shl0 ) |
89 | 0 | return; |
90 | | |
91 | 28 | const Expr *lhs = binop->getLHS(); |
92 | 28 | const Expr *rhs = binop->getRHS(); |
93 | 28 | if (rhs->isEvaluatable(Context)) { |
94 | 21 | e = lhs; |
95 | 21 | maxVal = rhs->EvaluateKnownConstInt(Context); |
96 | 21 | if (EvaluatesToZero(maxVal, opc)) |
97 | 2 | return; |
98 | 21 | } else if (7 (7 opc == BO_Add7 || opc == BO_Mul7 ) && |
99 | 7 | lhs->isEvaluatable(Context)) { |
100 | 7 | maxVal = lhs->EvaluateKnownConstInt(Context); |
101 | 7 | if (EvaluatesToZero(maxVal, opc)) |
102 | 0 | return; |
103 | 7 | e = rhs; |
104 | 7 | } else |
105 | 0 | return; |
106 | 28 | } else if (23 isa<DeclRefExpr, MemberExpr>(e)23 ) |
107 | 22 | break; |
108 | 1 | else |
109 | 1 | return; |
110 | 51 | } |
111 | | |
112 | 22 | if (mulop == nullptr) |
113 | 0 | return; |
114 | | |
115 | | // We've found the right structure of malloc argument, now save |
116 | | // the data so when the body of the function is completely available |
117 | | // we can check for comparisons. |
118 | | |
119 | 22 | PossibleMallocOverflows.push_back( |
120 | 22 | MallocOverflowCheck(TheCall, mulop, e, maxVal)); |
121 | 22 | } |
122 | | |
123 | | namespace { |
124 | | // A worker class for OutputPossibleOverflows. |
125 | | class CheckOverflowOps : |
126 | | public EvaluatedExprVisitor<CheckOverflowOps> { |
127 | | public: |
128 | | typedef SmallVectorImpl<MallocOverflowCheck> theVecType; |
129 | | |
130 | | private: |
131 | | theVecType &toScanFor; |
132 | | ASTContext &Context; |
133 | | |
134 | 22 | bool isIntZeroExpr(const Expr *E) const { |
135 | 22 | if (!E->getType()->isIntegralOrEnumerationType()) |
136 | 0 | return false; |
137 | 22 | Expr::EvalResult Result; |
138 | 22 | if (E->EvaluateAsInt(Result, Context)) |
139 | 11 | return Result.Val.getInt() == 0; |
140 | 11 | return false; |
141 | 22 | } |
142 | | |
143 | 20 | static const Decl *getDecl(const DeclRefExpr *DR) { return DR->getDecl(); } |
144 | 10 | static const Decl *getDecl(const MemberExpr *ME) { |
145 | 10 | return ME->getMemberDecl(); |
146 | 10 | } |
147 | | |
148 | | template <typename T1> |
149 | | void Erase(const T1 *DR, |
150 | 16 | llvm::function_ref<bool(const MallocOverflowCheck &)> Pred) { |
151 | 19 | auto P = [DR, Pred](const MallocOverflowCheck &Check) { |
152 | 19 | if (const auto *CheckDR = dyn_cast<T1>(Check.variable)) |
153 | 15 | return getDecl(CheckDR) == getDecl(DR) && Pred(Check)13 ; |
154 | 4 | return false; |
155 | 19 | }; MallocOverflowSecurityChecker.cpp:void (anonymous namespace)::CheckOverflowOps::Erase<clang::DeclRefExpr>(clang::DeclRefExpr const*, llvm::function_ref<bool ((anonymous namespace)::MallocOverflowCheck const&)>)::'lambda'((anonymous namespace)::MallocOverflowCheck const&)::operator()((anonymous namespace)::MallocOverflowCheck const&) const Line | Count | Source | 151 | 12 | auto P = [DR, Pred](const MallocOverflowCheck &Check) { | 152 | 12 | if (const auto *CheckDR = dyn_cast<T1>(Check.variable)) | 153 | 10 | return getDecl(CheckDR) == getDecl(DR) && Pred(Check)8 ; | 154 | 2 | return false; | 155 | 12 | }; |
MallocOverflowSecurityChecker.cpp:void (anonymous namespace)::CheckOverflowOps::Erase<clang::MemberExpr>(clang::MemberExpr const*, llvm::function_ref<bool ((anonymous namespace)::MallocOverflowCheck const&)>)::'lambda'((anonymous namespace)::MallocOverflowCheck const&)::operator()((anonymous namespace)::MallocOverflowCheck const&) const Line | Count | Source | 151 | 7 | auto P = [DR, Pred](const MallocOverflowCheck &Check) { | 152 | 7 | if (const auto *CheckDR = dyn_cast<T1>(Check.variable)) | 153 | 5 | return getDecl(CheckDR) == getDecl(DR) && Pred(Check); | 154 | 2 | return false; | 155 | 7 | }; |
|
156 | 16 | llvm::erase_if(toScanFor, P); |
157 | 16 | } MallocOverflowSecurityChecker.cpp:void (anonymous namespace)::CheckOverflowOps::Erase<clang::DeclRefExpr>(clang::DeclRefExpr const*, llvm::function_ref<bool ((anonymous namespace)::MallocOverflowCheck const&)>) Line | Count | Source | 150 | 11 | llvm::function_ref<bool(const MallocOverflowCheck &)> Pred) { | 151 | 11 | auto P = [DR, Pred](const MallocOverflowCheck &Check) { | 152 | 11 | if (const auto *CheckDR = dyn_cast<T1>(Check.variable)) | 153 | 11 | return getDecl(CheckDR) == getDecl(DR) && Pred(Check); | 154 | 11 | return false; | 155 | 11 | }; | 156 | 11 | llvm::erase_if(toScanFor, P); | 157 | 11 | } |
MallocOverflowSecurityChecker.cpp:void (anonymous namespace)::CheckOverflowOps::Erase<clang::MemberExpr>(clang::MemberExpr const*, llvm::function_ref<bool ((anonymous namespace)::MallocOverflowCheck const&)>) Line | Count | Source | 150 | 5 | llvm::function_ref<bool(const MallocOverflowCheck &)> Pred) { | 151 | 5 | auto P = [DR, Pred](const MallocOverflowCheck &Check) { | 152 | 5 | if (const auto *CheckDR = dyn_cast<T1>(Check.variable)) | 153 | 5 | return getDecl(CheckDR) == getDecl(DR) && Pred(Check); | 154 | 5 | return false; | 155 | 5 | }; | 156 | 5 | llvm::erase_if(toScanFor, P); | 157 | 5 | } |
|
158 | | |
159 | 20 | void CheckExpr(const Expr *E_p) { |
160 | 20 | const Expr *E = E_p->IgnoreParenImpCasts(); |
161 | 20 | const auto PrecedesMalloc = [E, this](const MallocOverflowCheck &c) { |
162 | 7 | return Context.getSourceManager().isBeforeInTranslationUnit( |
163 | 7 | E->getExprLoc(), c.call->getExprLoc()); |
164 | 7 | }; |
165 | 20 | if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) |
166 | 9 | Erase<DeclRefExpr>(DR, PrecedesMalloc); |
167 | 11 | else if (const auto *ME = dyn_cast<MemberExpr>(E)) { |
168 | 1 | Erase<MemberExpr>(ME, PrecedesMalloc); |
169 | 1 | } |
170 | 20 | } |
171 | | |
172 | | // Check if the argument to malloc is assigned a value |
173 | | // which cannot cause an overflow. |
174 | | // e.g., malloc (mul * x) and, |
175 | | // case 1: mul = <constant value> |
176 | | // case 2: mul = a/b, where b > x |
177 | 18 | void CheckAssignmentExpr(BinaryOperator *AssignEx) { |
178 | 18 | bool assignKnown = false; |
179 | 18 | bool numeratorKnown = false, denomKnown = false; |
180 | 18 | APSInt denomVal; |
181 | 18 | denomVal = 0; |
182 | | |
183 | | // Erase if the multiplicand was assigned a constant value. |
184 | 18 | const Expr *rhs = AssignEx->getRHS(); |
185 | 18 | if (rhs->isEvaluatable(Context)) |
186 | 6 | assignKnown = true; |
187 | | |
188 | | // Discard the report if the multiplicand was assigned a value, |
189 | | // that can never overflow after multiplication. e.g., the assignment |
190 | | // is a division operator and the denominator is > other multiplicand. |
191 | 18 | const Expr *rhse = rhs->IgnoreParenImpCasts(); |
192 | 18 | if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(rhse)) { |
193 | 4 | if (BOp->getOpcode() == BO_Div) { |
194 | 4 | const Expr *denom = BOp->getRHS()->IgnoreParenImpCasts(); |
195 | 4 | Expr::EvalResult Result; |
196 | 4 | if (denom->EvaluateAsInt(Result, Context)) { |
197 | 4 | denomVal = Result.Val.getInt(); |
198 | 4 | denomKnown = true; |
199 | 4 | } |
200 | 4 | const Expr *numerator = BOp->getLHS()->IgnoreParenImpCasts(); |
201 | 4 | if (numerator->isEvaluatable(Context)) |
202 | 2 | numeratorKnown = true; |
203 | 4 | } |
204 | 4 | } |
205 | 18 | if (!assignKnown && !denomKnown12 ) |
206 | 10 | return; |
207 | 8 | auto denomExtVal = denomVal.getExtValue(); |
208 | | |
209 | | // Ignore negative denominator. |
210 | 8 | if (denomExtVal < 0) |
211 | 0 | return; |
212 | | |
213 | 8 | const Expr *lhs = AssignEx->getLHS(); |
214 | 8 | const Expr *E = lhs->IgnoreParenImpCasts(); |
215 | | |
216 | 8 | auto pred = [assignKnown, numeratorKnown, |
217 | 8 | denomExtVal](const MallocOverflowCheck &Check) { |
218 | 6 | return assignKnown || |
219 | 6 | (2 numeratorKnown2 && (denomExtVal >= Check.maxVal.getExtValue())0 ); |
220 | 6 | }; |
221 | | |
222 | 8 | if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) |
223 | 2 | Erase<DeclRefExpr>(DR, pred); |
224 | 6 | else if (const auto *ME = dyn_cast<MemberExpr>(E)) |
225 | 4 | Erase<MemberExpr>(ME, pred); |
226 | 8 | } |
227 | | |
228 | | public: |
229 | 64 | void VisitBinaryOperator(BinaryOperator *E) { |
230 | 64 | if (E->isComparisonOp()) { |
231 | 11 | const Expr * lhs = E->getLHS(); |
232 | 11 | const Expr * rhs = E->getRHS(); |
233 | | // Ignore comparisons against zero, since they generally don't |
234 | | // protect against an overflow. |
235 | 11 | if (!isIntZeroExpr(lhs) && !isIntZeroExpr(rhs)) { |
236 | 10 | CheckExpr(lhs); |
237 | 10 | CheckExpr(rhs); |
238 | 10 | } |
239 | 11 | } |
240 | 64 | if (E->isAssignmentOp()) |
241 | 18 | CheckAssignmentExpr(E); |
242 | 64 | EvaluatedExprVisitor<CheckOverflowOps>::VisitBinaryOperator(E); |
243 | 64 | } |
244 | | |
245 | | /* We specifically ignore loop conditions, because they're typically |
246 | | not error checks. */ |
247 | 1 | void VisitWhileStmt(WhileStmt *S) { |
248 | 1 | return this->Visit(S->getBody()); |
249 | 1 | } |
250 | 2 | void VisitForStmt(ForStmt *S) { |
251 | 2 | return this->Visit(S->getBody()); |
252 | 2 | } |
253 | 1 | void VisitDoStmt(DoStmt *S) { |
254 | 1 | return this->Visit(S->getBody()); |
255 | 1 | } |
256 | | |
257 | | CheckOverflowOps(theVecType &v, ASTContext &ctx) |
258 | 20 | : EvaluatedExprVisitor<CheckOverflowOps>(ctx), |
259 | 20 | toScanFor(v), Context(ctx) |
260 | 20 | { } |
261 | | }; |
262 | | } |
263 | | |
264 | | // OutputPossibleOverflows - We've found a possible overflow earlier, |
265 | | // now check whether Body might contain a comparison which might be |
266 | | // preventing the overflow. |
267 | | // This doesn't do flow analysis, range analysis, or points-to analysis; it's |
268 | | // just a dumb "is there a comparison" scan. The aim here is to |
269 | | // detect the most blatent cases of overflow and educate the |
270 | | // programmer. |
271 | | void MallocOverflowSecurityChecker::OutputPossibleOverflows( |
272 | | SmallVectorImpl<MallocOverflowCheck> &PossibleMallocOverflows, |
273 | 24 | const Decl *D, BugReporter &BR, AnalysisManager &mgr) const { |
274 | | // By far the most common case: nothing to check. |
275 | 24 | if (PossibleMallocOverflows.empty()) |
276 | 4 | return; |
277 | | |
278 | | // Delete any possible overflows which have a comparison. |
279 | 20 | CheckOverflowOps c(PossibleMallocOverflows, BR.getContext()); |
280 | 20 | c.Visit(mgr.getAnalysisDeclContext(D)->getBody()); |
281 | | |
282 | | // Output warnings for all overflows that are left. |
283 | 20 | for (const MallocOverflowCheck &Check : PossibleMallocOverflows) { |
284 | 13 | BR.EmitBasicReport( |
285 | 13 | D, this, "malloc() size overflow", categories::UnixAPI, |
286 | 13 | "the computation of the size of the memory allocation may overflow", |
287 | 13 | PathDiagnosticLocation::createOperatorLoc(Check.mulop, |
288 | 13 | BR.getSourceManager()), |
289 | 13 | Check.mulop->getSourceRange()); |
290 | 13 | } |
291 | 20 | } |
292 | | |
293 | | void MallocOverflowSecurityChecker::checkASTCodeBody(const Decl *D, |
294 | | AnalysisManager &mgr, |
295 | 24 | BugReporter &BR) const { |
296 | | |
297 | 24 | CFG *cfg = mgr.getCFG(D); |
298 | 24 | if (!cfg) |
299 | 0 | return; |
300 | | |
301 | | // A list of variables referenced in possibly overflowing malloc operands. |
302 | 24 | SmallVector<MallocOverflowCheck, 2> PossibleMallocOverflows; |
303 | | |
304 | 135 | for (CFG::iterator it = cfg->begin(), ei = cfg->end(); it != ei; ++it111 ) { |
305 | 111 | CFGBlock *block = *it; |
306 | 111 | for (CFGBlock::iterator bi = block->begin(), be = block->end(); |
307 | 673 | bi != be; ++bi562 ) { |
308 | 562 | if (std::optional<CFGStmt> CS = bi->getAs<CFGStmt>()) { |
309 | 562 | if (const CallExpr *TheCall = dyn_cast<CallExpr>(CS->getStmt())) { |
310 | | // Get the callee. |
311 | 28 | const FunctionDecl *FD = TheCall->getDirectCallee(); |
312 | | |
313 | 28 | if (!FD) |
314 | 0 | continue; |
315 | | |
316 | | // Get the name of the callee. If it's a builtin, strip off the |
317 | | // prefix. |
318 | 28 | IdentifierInfo *FnInfo = FD->getIdentifier(); |
319 | 28 | if (!FnInfo) |
320 | 1 | continue; |
321 | | |
322 | 27 | if (FnInfo->isStr("malloc") || FnInfo->isStr("_MALLOC")2 ) { |
323 | 25 | if (TheCall->getNumArgs() == 1) |
324 | 25 | CheckMallocArgument(PossibleMallocOverflows, TheCall, |
325 | 25 | mgr.getASTContext()); |
326 | 25 | } |
327 | 27 | } |
328 | 562 | } |
329 | 562 | } |
330 | 111 | } |
331 | | |
332 | 24 | OutputPossibleOverflows(PossibleMallocOverflows, D, BR, mgr); |
333 | 24 | } |
334 | | |
335 | 4 | void ento::registerMallocOverflowSecurityChecker(CheckerManager &mgr) { |
336 | 4 | mgr.registerChecker<MallocOverflowSecurityChecker>(); |
337 | 4 | } |
338 | | |
339 | 8 | bool ento::shouldRegisterMallocOverflowSecurityChecker(const CheckerManager &mgr) { |
340 | 8 | return true; |
341 | 8 | } |