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 <utility>
28 
29 using namespace clang;
30 using namespace ento;
31 using llvm::APSInt;
32 
33 namespace {
34 struct MallocOverflowCheck {
35   const CallExpr *call;
36   const BinaryOperator *mulop;
37   const Expr *variable;
38   APSInt maxVal;
39 
40   MallocOverflowCheck(const CallExpr *call, const BinaryOperator *m,
41                       const Expr *v, APSInt val)
42       : call(call), mulop(m), variable(v), maxVal(std::move(val)) {}
43 };
44 
45 class MallocOverflowSecurityChecker : public Checker<check::ASTCodeBody> {
46 public:
47   void checkASTCodeBody(const Decl *D, AnalysisManager &mgr,
48                         BugReporter &BR) const;
49 
50   void CheckMallocArgument(
51       SmallVectorImpl<MallocOverflowCheck> &PossibleMallocOverflows,
52       const CallExpr *TheCall, ASTContext &Context) const;
53 
54   void OutputPossibleOverflows(
55     SmallVectorImpl<MallocOverflowCheck> &PossibleMallocOverflows,
56     const Decl *D, BugReporter &BR, AnalysisManager &mgr) const;
57 
58 };
59 } // end anonymous namespace
60 
61 // Return true for computations which evaluate to zero: e.g., mult by 0.
62 static inline bool EvaluatesToZero(APSInt &Val, BinaryOperatorKind op) {
63   return (op == BO_Mul) && (Val == 0);
64 }
65 
66 void MallocOverflowSecurityChecker::CheckMallocArgument(
67     SmallVectorImpl<MallocOverflowCheck> &PossibleMallocOverflows,
68     const CallExpr *TheCall, ASTContext &Context) const {
69 
70   /* Look for a linear combination with a single variable, and at least
71    one multiplication.
72    Reject anything that applies to the variable: an explicit cast,
73    conditional expression, an operation that could reduce the range
74    of the result, or anything too complicated :-).  */
75   const Expr *e = TheCall->getArg(0);
76   const BinaryOperator * mulop = nullptr;
77   APSInt maxVal;
78 
79   for (;;) {
80     maxVal = 0;
81     e = e->IgnoreParenImpCasts();
82     if (const BinaryOperator *binop = dyn_cast<BinaryOperator>(e)) {
83       BinaryOperatorKind opc = binop->getOpcode();
84       // TODO: ignore multiplications by 1, reject if multiplied by 0.
85       if (mulop == nullptr && opc == BO_Mul)
86         mulop = binop;
87       if (opc != BO_Mul && opc != BO_Add && opc != BO_Sub && opc != BO_Shl)
88         return;
89 
90       const Expr *lhs = binop->getLHS();
91       const Expr *rhs = binop->getRHS();
92       if (rhs->isEvaluatable(Context)) {
93         e = lhs;
94         maxVal = rhs->EvaluateKnownConstInt(Context);
95         if (EvaluatesToZero(maxVal, opc))
96           return;
97       } else if ((opc == BO_Add || opc == BO_Mul) &&
98                  lhs->isEvaluatable(Context)) {
99         maxVal = lhs->EvaluateKnownConstInt(Context);
100         if (EvaluatesToZero(maxVal, opc))
101           return;
102         e = rhs;
103       } else
104         return;
105     }
106     else if (isa<DeclRefExpr>(e) || isa<MemberExpr>(e))
107       break;
108     else
109       return;
110   }
111 
112   if (mulop == nullptr)
113     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   PossibleMallocOverflows.push_back(
120       MallocOverflowCheck(TheCall, mulop, e, maxVal));
121 }
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     bool isIntZeroExpr(const Expr *E) const {
135       if (!E->getType()->isIntegralOrEnumerationType())
136         return false;
137       Expr::EvalResult Result;
138       if (E->EvaluateAsInt(Result, Context))
139         return Result.Val.getInt() == 0;
140       return false;
141     }
142 
143     static const Decl *getDecl(const DeclRefExpr *DR) { return DR->getDecl(); }
144     static const Decl *getDecl(const MemberExpr *ME) {
145       return ME->getMemberDecl();
146     }
147 
148     template <typename T1>
149     void Erase(const T1 *DR,
150                llvm::function_ref<bool(const MallocOverflowCheck &)> Pred) {
151       auto P = [DR, Pred](const MallocOverflowCheck &Check) {
152         if (const auto *CheckDR = dyn_cast<T1>(Check.variable))
153           return getDecl(CheckDR) == getDecl(DR) && Pred(Check);
154         return false;
155       };
156       toScanFor.erase(std::remove_if(toScanFor.begin(), toScanFor.end(), P),
157                       toScanFor.end());
158     }
159 
160     void CheckExpr(const Expr *E_p) {
161       const Expr *E = E_p->IgnoreParenImpCasts();
162       const auto PrecedesMalloc = [E, this](const MallocOverflowCheck &c) {
163         return Context.getSourceManager().isBeforeInTranslationUnit(
164             E->getExprLoc(), c.call->getExprLoc());
165       };
166       if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E))
167         Erase<DeclRefExpr>(DR, PrecedesMalloc);
168       else if (const auto *ME = dyn_cast<MemberExpr>(E)) {
169         Erase<MemberExpr>(ME, PrecedesMalloc);
170       }
171     }
172 
173     // Check if the argument to malloc is assigned a value
174     // which cannot cause an overflow.
175     // e.g., malloc (mul * x) and,
176     // case 1: mul = <constant value>
177     // case 2: mul = a/b, where b > x
178     void CheckAssignmentExpr(BinaryOperator *AssignEx) {
179       bool assignKnown = false;
180       bool numeratorKnown = false, denomKnown = false;
181       APSInt denomVal;
182       denomVal = 0;
183 
184       // Erase if the multiplicand was assigned a constant value.
185       const Expr *rhs = AssignEx->getRHS();
186       if (rhs->isEvaluatable(Context))
187         assignKnown = true;
188 
189       // Discard the report if the multiplicand was assigned a value,
190       // that can never overflow after multiplication. e.g., the assignment
191       // is a division operator and the denominator is > other multiplicand.
192       const Expr *rhse = rhs->IgnoreParenImpCasts();
193       if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(rhse)) {
194         if (BOp->getOpcode() == BO_Div) {
195           const Expr *denom = BOp->getRHS()->IgnoreParenImpCasts();
196           Expr::EvalResult Result;
197           if (denom->EvaluateAsInt(Result, Context)) {
198             denomVal = Result.Val.getInt();
199             denomKnown = true;
200           }
201           const Expr *numerator = BOp->getLHS()->IgnoreParenImpCasts();
202           if (numerator->isEvaluatable(Context))
203             numeratorKnown = true;
204         }
205       }
206       if (!assignKnown && !denomKnown)
207         return;
208       auto denomExtVal = denomVal.getExtValue();
209 
210       // Ignore negative denominator.
211       if (denomExtVal < 0)
212         return;
213 
214       const Expr *lhs = AssignEx->getLHS();
215       const Expr *E = lhs->IgnoreParenImpCasts();
216 
217       auto pred = [assignKnown, numeratorKnown,
218                    denomExtVal](const MallocOverflowCheck &Check) {
219         return assignKnown ||
220                (numeratorKnown && (denomExtVal >= Check.maxVal.getExtValue()));
221       };
222 
223       if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E))
224         Erase<DeclRefExpr>(DR, pred);
225       else if (const auto *ME = dyn_cast<MemberExpr>(E))
226         Erase<MemberExpr>(ME, pred);
227     }
228 
229   public:
230     void VisitBinaryOperator(BinaryOperator *E) {
231       if (E->isComparisonOp()) {
232         const Expr * lhs = E->getLHS();
233         const Expr * rhs = E->getRHS();
234         // Ignore comparisons against zero, since they generally don't
235         // protect against an overflow.
236         if (!isIntZeroExpr(lhs) && !isIntZeroExpr(rhs)) {
237           CheckExpr(lhs);
238           CheckExpr(rhs);
239         }
240       }
241       if (E->isAssignmentOp())
242         CheckAssignmentExpr(E);
243       EvaluatedExprVisitor<CheckOverflowOps>::VisitBinaryOperator(E);
244     }
245 
246     /* We specifically ignore loop conditions, because they're typically
247      not error checks.  */
248     void VisitWhileStmt(WhileStmt *S) {
249       return this->Visit(S->getBody());
250     }
251     void VisitForStmt(ForStmt *S) {
252       return this->Visit(S->getBody());
253     }
254     void VisitDoStmt(DoStmt *S) {
255       return this->Visit(S->getBody());
256     }
257 
258     CheckOverflowOps(theVecType &v, ASTContext &ctx)
259     : EvaluatedExprVisitor<CheckOverflowOps>(ctx),
260       toScanFor(v), Context(ctx)
261     { }
262   };
263 }
264 
265 // OutputPossibleOverflows - We've found a possible overflow earlier,
266 // now check whether Body might contain a comparison which might be
267 // preventing the overflow.
268 // This doesn't do flow analysis, range analysis, or points-to analysis; it's
269 // just a dumb "is there a comparison" scan.  The aim here is to
270 // detect the most blatent cases of overflow and educate the
271 // programmer.
272 void MallocOverflowSecurityChecker::OutputPossibleOverflows(
273   SmallVectorImpl<MallocOverflowCheck> &PossibleMallocOverflows,
274   const Decl *D, BugReporter &BR, AnalysisManager &mgr) const {
275   // By far the most common case: nothing to check.
276   if (PossibleMallocOverflows.empty())
277     return;
278 
279   // Delete any possible overflows which have a comparison.
280   CheckOverflowOps c(PossibleMallocOverflows, BR.getContext());
281   c.Visit(mgr.getAnalysisDeclContext(D)->getBody());
282 
283   // Output warnings for all overflows that are left.
284   for (CheckOverflowOps::theVecType::iterator
285        i = PossibleMallocOverflows.begin(),
286        e = PossibleMallocOverflows.end();
287        i != e;
288        ++i) {
289     BR.EmitBasicReport(
290         D, this, "malloc() size overflow", categories::UnixAPI,
291         "the computation of the size of the memory allocation may overflow",
292         PathDiagnosticLocation::createOperatorLoc(i->mulop,
293                                                   BR.getSourceManager()),
294         i->mulop->getSourceRange());
295   }
296 }
297 
298 void MallocOverflowSecurityChecker::checkASTCodeBody(const Decl *D,
299                                              AnalysisManager &mgr,
300                                              BugReporter &BR) const {
301 
302   CFG *cfg = mgr.getCFG(D);
303   if (!cfg)
304     return;
305 
306   // A list of variables referenced in possibly overflowing malloc operands.
307   SmallVector<MallocOverflowCheck, 2> PossibleMallocOverflows;
308 
309   for (CFG::iterator it = cfg->begin(), ei = cfg->end(); it != ei; ++it) {
310     CFGBlock *block = *it;
311     for (CFGBlock::iterator bi = block->begin(), be = block->end();
312          bi != be; ++bi) {
313       if (Optional<CFGStmt> CS = bi->getAs<CFGStmt>()) {
314         if (const CallExpr *TheCall = dyn_cast<CallExpr>(CS->getStmt())) {
315           // Get the callee.
316           const FunctionDecl *FD = TheCall->getDirectCallee();
317 
318           if (!FD)
319             continue;
320 
321           // Get the name of the callee. If it's a builtin, strip off the prefix.
322           IdentifierInfo *FnInfo = FD->getIdentifier();
323           if (!FnInfo)
324             continue;
325 
326           if (FnInfo->isStr ("malloc") || FnInfo->isStr ("_MALLOC")) {
327             if (TheCall->getNumArgs() == 1)
328               CheckMallocArgument(PossibleMallocOverflows, TheCall,
329                                   mgr.getASTContext());
330           }
331         }
332       }
333     }
334   }
335 
336   OutputPossibleOverflows(PossibleMallocOverflows, D, BR, mgr);
337 }
338 
339 void ento::registerMallocOverflowSecurityChecker(CheckerManager &mgr) {
340   mgr.registerChecker<MallocOverflowSecurityChecker>();
341 }
342 
343 bool ento::shouldRegisterMallocOverflowSecurityChecker(const CheckerManager &mgr) {
344   return true;
345 }
346