blob: 8c4c7cde551e08616fdc46655c8e5e43cb553430 [file] [log] [blame]
Ted Kremenek1c2fb272011-08-03 20:17:43 +00001// 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"
Ted Kremenek1c2fb272011-08-03 20:17:43 +000023#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/StaticAnalyzer/Core/Checker.h"
25#include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
Devin Coughlin683dfd32015-09-23 23:27:55 +000026#include "llvm/ADT/APSInt.h"
Ted Kremenek1c2fb272011-08-03 20:17:43 +000027#include "llvm/ADT/SmallVector.h"
Benjamin Kramercfeacf52016-05-27 14:27:13 +000028#include <utility>
Ted Kremenek1c2fb272011-08-03 20:17:43 +000029
30using namespace clang;
31using namespace ento;
Devin Coughlin683dfd32015-09-23 23:27:55 +000032using llvm::APInt;
33using llvm::APSInt;
Ted Kremenek1c2fb272011-08-03 20:17:43 +000034
35namespace {
36struct MallocOverflowCheck {
37 const BinaryOperator *mulop;
38 const Expr *variable;
Devin Coughlin683dfd32015-09-23 23:27:55 +000039 APSInt maxVal;
Ted Kremenek1c2fb272011-08-03 20:17:43 +000040
Devin Coughlin683dfd32015-09-23 23:27:55 +000041 MallocOverflowCheck(const BinaryOperator *m, const Expr *v, APSInt val)
Benjamin Kramercfeacf52016-05-27 14:27:13 +000042 : mulop(m), variable(v), maxVal(std::move(val)) {}
Ted Kremenek1c2fb272011-08-03 20:17:43 +000043};
44
45class MallocOverflowSecurityChecker : public Checker<check::ASTCodeBody> {
46public:
47 void checkASTCodeBody(const Decl *D, AnalysisManager &mgr,
48 BugReporter &BR) const;
49
50 void CheckMallocArgument(
Dmitri Gribenkof8579502013-01-12 19:30:44 +000051 SmallVectorImpl<MallocOverflowCheck> &PossibleMallocOverflows,
Ted Kremenek1c2fb272011-08-03 20:17:43 +000052 const Expr *TheArgument, ASTContext &Context) const;
53
54 void OutputPossibleOverflows(
Dmitri Gribenkof8579502013-01-12 19:30:44 +000055 SmallVectorImpl<MallocOverflowCheck> &PossibleMallocOverflows,
Ted Kremenek1c2fb272011-08-03 20:17:43 +000056 const Decl *D, BugReporter &BR, AnalysisManager &mgr) const;
57
58};
59} // end anonymous namespace
60
Devin Coughlin683dfd32015-09-23 23:27:55 +000061// Return true for computations which evaluate to zero: e.g., mult by 0.
62static inline bool EvaluatesToZero(APSInt &Val, BinaryOperatorKind op) {
63 return (op == BO_Mul) && (Val == 0);
64}
65
Ted Kremenek1c2fb272011-08-03 20:17:43 +000066void MallocOverflowSecurityChecker::CheckMallocArgument(
Dmitri Gribenkof8579502013-01-12 19:30:44 +000067 SmallVectorImpl<MallocOverflowCheck> &PossibleMallocOverflows,
Ted Kremenek1c2fb272011-08-03 20:17:43 +000068 const Expr *TheArgument,
69 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 :-). */
Devin Coughlin683dfd32015-09-23 23:27:55 +000076 const Expr *e = TheArgument;
Craig Topper0dbb7832014-05-27 02:45:47 +000077 const BinaryOperator * mulop = nullptr;
Devin Coughlin683dfd32015-09-23 23:27:55 +000078 APSInt maxVal;
Ted Kremenek1c2fb272011-08-03 20:17:43 +000079
80 for (;;) {
Devin Coughlin683dfd32015-09-23 23:27:55 +000081 maxVal = 0;
Ted Kremenek1c2fb272011-08-03 20:17:43 +000082 e = e->IgnoreParenImpCasts();
Devin Coughlin683dfd32015-09-23 23:27:55 +000083 if (const BinaryOperator *binop = dyn_cast<BinaryOperator>(e)) {
Ted Kremenek1c2fb272011-08-03 20:17:43 +000084 BinaryOperatorKind opc = binop->getOpcode();
85 // TODO: ignore multiplications by 1, reject if multiplied by 0.
Craig Topper0dbb7832014-05-27 02:45:47 +000086 if (mulop == nullptr && opc == BO_Mul)
Ted Kremenek1c2fb272011-08-03 20:17:43 +000087 mulop = binop;
88 if (opc != BO_Mul && opc != BO_Add && opc != BO_Sub && opc != BO_Shl)
89 return;
90
91 const Expr *lhs = binop->getLHS();
92 const Expr *rhs = binop->getRHS();
Devin Coughlin683dfd32015-09-23 23:27:55 +000093 if (rhs->isEvaluatable(Context)) {
Ted Kremenek1c2fb272011-08-03 20:17:43 +000094 e = lhs;
Devin Coughlin683dfd32015-09-23 23:27:55 +000095 maxVal = rhs->EvaluateKnownConstInt(Context);
96 if (EvaluatesToZero(maxVal, opc))
97 return;
98 } else if ((opc == BO_Add || opc == BO_Mul) &&
99 lhs->isEvaluatable(Context)) {
100 maxVal = lhs->EvaluateKnownConstInt(Context);
101 if (EvaluatesToZero(maxVal, opc))
102 return;
Ted Kremenek1c2fb272011-08-03 20:17:43 +0000103 e = rhs;
Devin Coughlin683dfd32015-09-23 23:27:55 +0000104 } else
Ted Kremenek1c2fb272011-08-03 20:17:43 +0000105 return;
106 }
107 else if (isa<DeclRefExpr>(e) || isa<MemberExpr>(e))
108 break;
109 else
110 return;
111 }
112
Craig Topper0dbb7832014-05-27 02:45:47 +0000113 if (mulop == nullptr)
Ted Kremenek1c2fb272011-08-03 20:17:43 +0000114 return;
115
116 // We've found the right structure of malloc argument, now save
117 // the data so when the body of the function is completely available
118 // we can check for comparisons.
119
120 // TODO: Could push this into the innermost scope where 'e' is
121 // defined, rather than the whole function.
Devin Coughlin683dfd32015-09-23 23:27:55 +0000122 PossibleMallocOverflows.push_back(MallocOverflowCheck(mulop, e, maxVal));
Ted Kremenek1c2fb272011-08-03 20:17:43 +0000123}
124
125namespace {
126// A worker class for OutputPossibleOverflows.
127class CheckOverflowOps :
128 public EvaluatedExprVisitor<CheckOverflowOps> {
129public:
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000130 typedef SmallVectorImpl<MallocOverflowCheck> theVecType;
Ted Kremenek1c2fb272011-08-03 20:17:43 +0000131
132private:
133 theVecType &toScanFor;
134 ASTContext &Context;
135
136 bool isIntZeroExpr(const Expr *E) const {
Richard Smithcaf33902011-10-10 18:28:20 +0000137 if (!E->getType()->isIntegralOrEnumerationType())
138 return false;
139 llvm::APSInt Result;
140 if (E->EvaluateAsInt(Result, Context))
141 return Result == 0;
142 return false;
Ted Kremenek1c2fb272011-08-03 20:17:43 +0000143 }
144
Devin Coughlin683dfd32015-09-23 23:27:55 +0000145 const Decl *getDecl(const DeclRefExpr *DR) { return DR->getDecl(); }
Ted Kremenek1c2fb272011-08-03 20:17:43 +0000146
Devin Coughlin683dfd32015-09-23 23:27:55 +0000147 const Decl *getDecl(const MemberExpr *ME) { return ME->getMemberDecl(); }
148
149 template <typename T1>
150 void Erase(const T1 *DR, std::function<bool(theVecType::iterator)> pred) {
Ted Kremenek1c2fb272011-08-03 20:17:43 +0000151 theVecType::iterator i = toScanFor.end();
152 theVecType::iterator e = toScanFor.begin();
Devin Coughlin683dfd32015-09-23 23:27:55 +0000153 while (i != e) {
154 --i;
155 if (const T1 *DR_i = dyn_cast<T1>(i->variable)) {
156 if ((getDecl(DR_i) == getDecl(DR)) && pred(i))
157 i = toScanFor.erase(i);
158 }
159 }
160 }
Ted Kremenek1c2fb272011-08-03 20:17:43 +0000161
Devin Coughlin683dfd32015-09-23 23:27:55 +0000162 void CheckExpr(const Expr *E_p) {
163 auto PredTrue = [](theVecType::iterator) -> bool { return true; };
164 const Expr *E = E_p->IgnoreParenImpCasts();
165 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E))
166 Erase<DeclRefExpr>(DR, PredTrue);
Benjamin Kramera008d3a2015-04-10 11:37:55 +0000167 else if (const auto *ME = dyn_cast<MemberExpr>(E)) {
Devin Coughlin683dfd32015-09-23 23:27:55 +0000168 Erase<MemberExpr>(ME, PredTrue);
169 }
170 }
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 void CheckAssignmentExpr(BinaryOperator *AssignEx) {
178 bool assignKnown = false;
179 bool numeratorKnown = false, denomKnown = false;
180 APSInt denomVal;
181 denomVal = 0;
182
183 // Erase if the multiplicand was assigned a constant value.
184 const Expr *rhs = AssignEx->getRHS();
185 if (rhs->isEvaluatable(Context))
186 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 const Expr *rhse = rhs->IgnoreParenImpCasts();
192 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(rhse)) {
193 if (BOp->getOpcode() == BO_Div) {
194 const Expr *denom = BOp->getRHS()->IgnoreParenImpCasts();
195 if (denom->EvaluateAsInt(denomVal, Context))
196 denomKnown = true;
197 const Expr *numerator = BOp->getLHS()->IgnoreParenImpCasts();
198 if (numerator->isEvaluatable(Context))
199 numeratorKnown = true;
Ted Kremenek1c2fb272011-08-03 20:17:43 +0000200 }
201 }
Devin Coughlin683dfd32015-09-23 23:27:55 +0000202 if (!assignKnown && !denomKnown)
203 return;
204 auto denomExtVal = denomVal.getExtValue();
205
206 // Ignore negative denominator.
207 if (denomExtVal < 0)
208 return;
209
210 const Expr *lhs = AssignEx->getLHS();
211 const Expr *E = lhs->IgnoreParenImpCasts();
212
213 auto pred = [assignKnown, numeratorKnown,
214 denomExtVal](theVecType::iterator i) {
215 return assignKnown ||
216 (numeratorKnown && (denomExtVal >= i->maxVal.getExtValue()));
217 };
218
219 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E))
220 Erase<DeclRefExpr>(DR, pred);
221 else if (const auto *ME = dyn_cast<MemberExpr>(E))
222 Erase<MemberExpr>(ME, pred);
Ted Kremenek1c2fb272011-08-03 20:17:43 +0000223 }
224
225 public:
226 void VisitBinaryOperator(BinaryOperator *E) {
227 if (E->isComparisonOp()) {
228 const Expr * lhs = E->getLHS();
229 const Expr * rhs = E->getRHS();
230 // Ignore comparisons against zero, since they generally don't
231 // protect against an overflow.
Devin Coughlin683dfd32015-09-23 23:27:55 +0000232 if (!isIntZeroExpr(lhs) && !isIntZeroExpr(rhs)) {
Ted Kremenek1c2fb272011-08-03 20:17:43 +0000233 CheckExpr(lhs);
234 CheckExpr(rhs);
235 }
236 }
Devin Coughlin683dfd32015-09-23 23:27:55 +0000237 if (E->isAssignmentOp())
238 CheckAssignmentExpr(E);
Ted Kremenek1c2fb272011-08-03 20:17:43 +0000239 EvaluatedExprVisitor<CheckOverflowOps>::VisitBinaryOperator(E);
240 }
241
242 /* We specifically ignore loop conditions, because they're typically
243 not error checks. */
244 void VisitWhileStmt(WhileStmt *S) {
245 return this->Visit(S->getBody());
246 }
247 void VisitForStmt(ForStmt *S) {
248 return this->Visit(S->getBody());
249 }
250 void VisitDoStmt(DoStmt *S) {
251 return this->Visit(S->getBody());
252 }
253
254 CheckOverflowOps(theVecType &v, ASTContext &ctx)
255 : EvaluatedExprVisitor<CheckOverflowOps>(ctx),
256 toScanFor(v), Context(ctx)
257 { }
258 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000259}
Ted Kremenek1c2fb272011-08-03 20:17:43 +0000260
261// OutputPossibleOverflows - We've found a possible overflow earlier,
262// now check whether Body might contain a comparison which might be
263// preventing the overflow.
264// This doesn't do flow analysis, range analysis, or points-to analysis; it's
265// just a dumb "is there a comparison" scan. The aim here is to
266// detect the most blatent cases of overflow and educate the
267// programmer.
268void MallocOverflowSecurityChecker::OutputPossibleOverflows(
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000269 SmallVectorImpl<MallocOverflowCheck> &PossibleMallocOverflows,
Ted Kremenek1c2fb272011-08-03 20:17:43 +0000270 const Decl *D, BugReporter &BR, AnalysisManager &mgr) const {
271 // By far the most common case: nothing to check.
272 if (PossibleMallocOverflows.empty())
273 return;
274
275 // Delete any possible overflows which have a comparison.
276 CheckOverflowOps c(PossibleMallocOverflows, BR.getContext());
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000277 c.Visit(mgr.getAnalysisDeclContext(D)->getBody());
Ted Kremenek1c2fb272011-08-03 20:17:43 +0000278
279 // Output warnings for all overflows that are left.
280 for (CheckOverflowOps::theVecType::iterator
281 i = PossibleMallocOverflows.begin(),
282 e = PossibleMallocOverflows.end();
283 i != e;
284 ++i) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000285 BR.EmitBasicReport(
286 D, this, "malloc() size overflow", categories::UnixAPI,
287 "the computation of the size of the memory allocation may overflow",
288 PathDiagnosticLocation::createOperatorLoc(i->mulop,
289 BR.getSourceManager()),
290 i->mulop->getSourceRange());
Ted Kremenek1c2fb272011-08-03 20:17:43 +0000291 }
292}
293
294void MallocOverflowSecurityChecker::checkASTCodeBody(const Decl *D,
295 AnalysisManager &mgr,
296 BugReporter &BR) const {
297
298 CFG *cfg = mgr.getCFG(D);
299 if (!cfg)
300 return;
301
302 // A list of variables referenced in possibly overflowing malloc operands.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000303 SmallVector<MallocOverflowCheck, 2> PossibleMallocOverflows;
Ted Kremenek1c2fb272011-08-03 20:17:43 +0000304
305 for (CFG::iterator it = cfg->begin(), ei = cfg->end(); it != ei; ++it) {
306 CFGBlock *block = *it;
307 for (CFGBlock::iterator bi = block->begin(), be = block->end();
308 bi != be; ++bi) {
David Blaikie00be69a2013-02-23 00:29:34 +0000309 if (Optional<CFGStmt> CS = bi->getAs<CFGStmt>()) {
310 if (const CallExpr *TheCall = dyn_cast<CallExpr>(CS->getStmt())) {
Ted Kremenek1c2fb272011-08-03 20:17:43 +0000311 // Get the callee.
312 const FunctionDecl *FD = TheCall->getDirectCallee();
313
314 if (!FD)
Devin Coughlin683dfd32015-09-23 23:27:55 +0000315 continue;
Ted Kremenek1c2fb272011-08-03 20:17:43 +0000316
317 // Get the name of the callee. If it's a builtin, strip off the prefix.
318 IdentifierInfo *FnInfo = FD->getIdentifier();
Anna Zaks0070c6d2011-09-27 22:25:01 +0000319 if (!FnInfo)
Devin Coughlin683dfd32015-09-23 23:27:55 +0000320 continue;
Ted Kremenek1c2fb272011-08-03 20:17:43 +0000321
322 if (FnInfo->isStr ("malloc") || FnInfo->isStr ("_MALLOC")) {
323 if (TheCall->getNumArgs() == 1)
324 CheckMallocArgument(PossibleMallocOverflows, TheCall->getArg(0),
325 mgr.getASTContext());
326 }
327 }
328 }
329 }
330 }
331
332 OutputPossibleOverflows(PossibleMallocOverflows, D, BR, mgr);
333}
334
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000335void
336ento::registerMallocOverflowSecurityChecker(CheckerManager &mgr) {
Ted Kremenek1c2fb272011-08-03 20:17:43 +0000337 mgr.registerChecker<MallocOverflowSecurityChecker>();
338}