1 // MallocOverflowSecurityChecker.cpp - Check for malloc overflows -*- C++ -*-=//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This checker detects a common memory allocation security flaw.
11 // Suppose 'unsigned int n' comes from an untrusted source. If the
12 // code looks like 'malloc (n * 4)', and an attacker can make 'n' be
13 // say MAX_UINT/4+2, then instead of allocating the correct 'n' 4-byte
14 // elements, this will actually allocate only two because of overflow.
15 // Then when the rest of the program attempts to store values past the
16 // second element, these values will actually overwrite other items in
17 // the heap, probably allowing the attacker to execute arbitrary code.
18 //
19 //===----------------------------------------------------------------------===//
20 
21 #include "ClangSACheckers.h"
22 #include "clang/AST/EvaluatedExprVisitor.h"
23 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
24 #include "clang/StaticAnalyzer/Core/Checker.h"
25 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
26 #include "llvm/ADT/APSInt.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include <utility>
29 
30 using namespace clang;
31 using namespace ento;
32 using llvm::APSInt;
33 
34 namespace {
35 struct MallocOverflowCheck {
36   const BinaryOperator *mulop;
37   const Expr *variable;
38   APSInt maxVal;
39 
40   MallocOverflowCheck(const BinaryOperator *m, const Expr *v, APSInt val)
41       : mulop(m), variable(v), maxVal(std::move(val)) {}
42 };
43 
44 class MallocOverflowSecurityChecker : public Checker<check::ASTCodeBody> {
45 public:
46   void checkASTCodeBody(const Decl *D, AnalysisManager &mgr,
47                         BugReporter &BR) const;
48 
49   void CheckMallocArgument(
50     SmallVectorImpl<MallocOverflowCheck> &PossibleMallocOverflows,
51     const Expr *TheArgument, ASTContext &Context) const;
52 
53   void OutputPossibleOverflows(
54     SmallVectorImpl<MallocOverflowCheck> &PossibleMallocOverflows,
55     const Decl *D, BugReporter &BR, AnalysisManager &mgr) const;
56 
57 };
58 } // end anonymous namespace
59 
60 // Return true for computations which evaluate to zero: e.g., mult by 0.
61 static inline bool EvaluatesToZero(APSInt &Val, BinaryOperatorKind op) {
62   return (op == BO_Mul) && (Val == 0);
63 }
64 
65 void MallocOverflowSecurityChecker::CheckMallocArgument(
66   SmallVectorImpl<MallocOverflowCheck> &PossibleMallocOverflows,
67   const Expr *TheArgument,
68   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 = TheArgument;
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   // TODO: Could push this into the innermost scope where 'e' is
120   // defined, rather than the whole function.
121   PossibleMallocOverflows.push_back(MallocOverflowCheck(mulop, e, maxVal));
122 }
123 
124 namespace {
125 // A worker class for OutputPossibleOverflows.
126 class CheckOverflowOps :
127   public EvaluatedExprVisitor<CheckOverflowOps> {
128 public:
129   typedef SmallVectorImpl<MallocOverflowCheck> theVecType;
130 
131 private:
132     theVecType &toScanFor;
133     ASTContext &Context;
134 
135     bool isIntZeroExpr(const Expr *E) const {
136       if (!E->getType()->isIntegralOrEnumerationType())
137         return false;
138       llvm::APSInt Result;
139       if (E->EvaluateAsInt(Result, Context))
140         return Result == 0;
141       return false;
142     }
143 
144     const Decl *getDecl(const DeclRefExpr *DR) { return DR->getDecl(); }
145 
146     const Decl *getDecl(const MemberExpr *ME) { return ME->getMemberDecl(); }
147 
148     template <typename T1>
149     void Erase(const T1 *DR,
150                llvm::function_ref<bool(const MallocOverflowCheck &)> Pred =
151                    [](const MallocOverflowCheck &) { return true; }) {
152       auto P = [this, DR, Pred](const MallocOverflowCheck &Check) {
153         if (const auto *CheckDR = dyn_cast<T1>(Check.variable))
154           return getDecl(CheckDR) == getDecl(DR) && Pred(Check);
155         return false;
156       };
157       toScanFor.erase(std::remove_if(toScanFor.begin(), toScanFor.end(), P),
158                       toScanFor.end());
159     }
160 
161     void CheckExpr(const Expr *E_p) {
162       const Expr *E = E_p->IgnoreParenImpCasts();
163       if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E))
164         Erase<DeclRefExpr>(DR);
165       else if (const auto *ME = dyn_cast<MemberExpr>(E)) {
166         Erase<MemberExpr>(ME);
167       }
168     }
169 
170     // Check if the argument to malloc is assigned a value
171     // which cannot cause an overflow.
172     // e.g., malloc (mul * x) and,
173     // case 1: mul = <constant value>
174     // case 2: mul = a/b, where b > x
175     void CheckAssignmentExpr(BinaryOperator *AssignEx) {
176       bool assignKnown = false;
177       bool numeratorKnown = false, denomKnown = false;
178       APSInt denomVal;
179       denomVal = 0;
180 
181       // Erase if the multiplicand was assigned a constant value.
182       const Expr *rhs = AssignEx->getRHS();
183       if (rhs->isEvaluatable(Context))
184         assignKnown = true;
185 
186       // Discard the report if the multiplicand was assigned a value,
187       // that can never overflow after multiplication. e.g., the assignment
188       // is a division operator and the denominator is > other multiplicand.
189       const Expr *rhse = rhs->IgnoreParenImpCasts();
190       if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(rhse)) {
191         if (BOp->getOpcode() == BO_Div) {
192           const Expr *denom = BOp->getRHS()->IgnoreParenImpCasts();
193           if (denom->EvaluateAsInt(denomVal, Context))
194             denomKnown = true;
195           const Expr *numerator = BOp->getLHS()->IgnoreParenImpCasts();
196           if (numerator->isEvaluatable(Context))
197             numeratorKnown = true;
198         }
199       }
200       if (!assignKnown && !denomKnown)
201         return;
202       auto denomExtVal = denomVal.getExtValue();
203 
204       // Ignore negative denominator.
205       if (denomExtVal < 0)
206         return;
207 
208       const Expr *lhs = AssignEx->getLHS();
209       const Expr *E = lhs->IgnoreParenImpCasts();
210 
211       auto pred = [assignKnown, numeratorKnown,
212                    denomExtVal](const MallocOverflowCheck &Check) {
213         return assignKnown ||
214                (numeratorKnown && (denomExtVal >= Check.maxVal.getExtValue()));
215       };
216 
217       if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E))
218         Erase<DeclRefExpr>(DR, pred);
219       else if (const auto *ME = dyn_cast<MemberExpr>(E))
220         Erase<MemberExpr>(ME, pred);
221     }
222 
223   public:
224     void VisitBinaryOperator(BinaryOperator *E) {
225       if (E->isComparisonOp()) {
226         const Expr * lhs = E->getLHS();
227         const Expr * rhs = E->getRHS();
228         // Ignore comparisons against zero, since they generally don't
229         // protect against an overflow.
230         if (!isIntZeroExpr(lhs) && !isIntZeroExpr(rhs)) {
231           CheckExpr(lhs);
232           CheckExpr(rhs);
233         }
234       }
235       if (E->isAssignmentOp())
236         CheckAssignmentExpr(E);
237       EvaluatedExprVisitor<CheckOverflowOps>::VisitBinaryOperator(E);
238     }
239 
240     /* We specifically ignore loop conditions, because they're typically
241      not error checks.  */
242     void VisitWhileStmt(WhileStmt *S) {
243       return this->Visit(S->getBody());
244     }
245     void VisitForStmt(ForStmt *S) {
246       return this->Visit(S->getBody());
247     }
248     void VisitDoStmt(DoStmt *S) {
249       return this->Visit(S->getBody());
250     }
251 
252     CheckOverflowOps(theVecType &v, ASTContext &ctx)
253     : EvaluatedExprVisitor<CheckOverflowOps>(ctx),
254       toScanFor(v), Context(ctx)
255     { }
256   };
257 }
258 
259 // OutputPossibleOverflows - We've found a possible overflow earlier,
260 // now check whether Body might contain a comparison which might be
261 // preventing the overflow.
262 // This doesn't do flow analysis, range analysis, or points-to analysis; it's
263 // just a dumb "is there a comparison" scan.  The aim here is to
264 // detect the most blatent cases of overflow and educate the
265 // programmer.
266 void MallocOverflowSecurityChecker::OutputPossibleOverflows(
267   SmallVectorImpl<MallocOverflowCheck> &PossibleMallocOverflows,
268   const Decl *D, BugReporter &BR, AnalysisManager &mgr) const {
269   // By far the most common case: nothing to check.
270   if (PossibleMallocOverflows.empty())
271     return;
272 
273   // Delete any possible overflows which have a comparison.
274   CheckOverflowOps c(PossibleMallocOverflows, BR.getContext());
275   c.Visit(mgr.getAnalysisDeclContext(D)->getBody());
276 
277   // Output warnings for all overflows that are left.
278   for (CheckOverflowOps::theVecType::iterator
279        i = PossibleMallocOverflows.begin(),
280        e = PossibleMallocOverflows.end();
281        i != e;
282        ++i) {
283     BR.EmitBasicReport(
284         D, this, "malloc() size overflow", categories::UnixAPI,
285         "the computation of the size of the memory allocation may overflow",
286         PathDiagnosticLocation::createOperatorLoc(i->mulop,
287                                                   BR.getSourceManager()),
288         i->mulop->getSourceRange());
289   }
290 }
291 
292 void MallocOverflowSecurityChecker::checkASTCodeBody(const Decl *D,
293                                              AnalysisManager &mgr,
294                                              BugReporter &BR) const {
295 
296   CFG *cfg = mgr.getCFG(D);
297   if (!cfg)
298     return;
299 
300   // A list of variables referenced in possibly overflowing malloc operands.
301   SmallVector<MallocOverflowCheck, 2> PossibleMallocOverflows;
302 
303   for (CFG::iterator it = cfg->begin(), ei = cfg->end(); it != ei; ++it) {
304     CFGBlock *block = *it;
305     for (CFGBlock::iterator bi = block->begin(), be = block->end();
306          bi != be; ++bi) {
307       if (Optional<CFGStmt> CS = bi->getAs<CFGStmt>()) {
308         if (const CallExpr *TheCall = dyn_cast<CallExpr>(CS->getStmt())) {
309           // Get the callee.
310           const FunctionDecl *FD = TheCall->getDirectCallee();
311 
312           if (!FD)
313             continue;
314 
315           // Get the name of the callee. If it's a builtin, strip off the prefix.
316           IdentifierInfo *FnInfo = FD->getIdentifier();
317           if (!FnInfo)
318             continue;
319 
320           if (FnInfo->isStr ("malloc") || FnInfo->isStr ("_MALLOC")) {
321             if (TheCall->getNumArgs() == 1)
322               CheckMallocArgument(PossibleMallocOverflows, TheCall->getArg(0),
323                                   mgr.getASTContext());
324           }
325         }
326       }
327     }
328   }
329 
330   OutputPossibleOverflows(PossibleMallocOverflows, D, BR, mgr);
331 }
332 
333 void
334 ento::registerMallocOverflowSecurityChecker(CheckerManager &mgr) {
335   mgr.registerChecker<MallocOverflowSecurityChecker>();
336 }
337