1 // MallocOverflowSecurityChecker.cpp - Check for malloc overflows -*- C++ -*-=//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
19 //===----------------------------------------------------------------------===//
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/SmallVector.h"
28 using namespace clang;
32 struct MallocOverflowCheck {
33 const BinaryOperator *mulop;
36 MallocOverflowCheck (const BinaryOperator *m, const Expr *v)
37 : mulop(m), variable (v)
41 class MallocOverflowSecurityChecker : public Checker<check::ASTCodeBody> {
43 void checkASTCodeBody(const Decl *D, AnalysisManager &mgr,
44 BugReporter &BR) const;
46 void CheckMallocArgument(
47 SmallVectorImpl<MallocOverflowCheck> &PossibleMallocOverflows,
48 const Expr *TheArgument, ASTContext &Context) const;
50 void OutputPossibleOverflows(
51 SmallVectorImpl<MallocOverflowCheck> &PossibleMallocOverflows,
52 const Decl *D, BugReporter &BR, AnalysisManager &mgr) const;
55 } // end anonymous namespace
57 void MallocOverflowSecurityChecker::CheckMallocArgument(
58 SmallVectorImpl<MallocOverflowCheck> &PossibleMallocOverflows,
59 const Expr *TheArgument,
60 ASTContext &Context) const {
62 /* Look for a linear combination with a single variable, and at least
64 Reject anything that applies to the variable: an explicit cast,
65 conditional expression, an operation that could reduce the range
66 of the result, or anything too complicated :-). */
67 const Expr * e = TheArgument;
68 const BinaryOperator * mulop = NULL;
71 e = e->IgnoreParenImpCasts();
72 if (isa<BinaryOperator>(e)) {
73 const BinaryOperator * binop = dyn_cast<BinaryOperator>(e);
74 BinaryOperatorKind opc = binop->getOpcode();
75 // TODO: ignore multiplications by 1, reject if multiplied by 0.
76 if (mulop == NULL && opc == BO_Mul)
78 if (opc != BO_Mul && opc != BO_Add && opc != BO_Sub && opc != BO_Shl)
81 const Expr *lhs = binop->getLHS();
82 const Expr *rhs = binop->getRHS();
83 if (rhs->isEvaluatable(Context))
85 else if ((opc == BO_Add || opc == BO_Mul)
86 && lhs->isEvaluatable(Context))
91 else if (isa<DeclRefExpr>(e) || isa<MemberExpr>(e))
100 // We've found the right structure of malloc argument, now save
101 // the data so when the body of the function is completely available
102 // we can check for comparisons.
104 // TODO: Could push this into the innermost scope where 'e' is
105 // defined, rather than the whole function.
106 PossibleMallocOverflows.push_back(MallocOverflowCheck(mulop, e));
110 // A worker class for OutputPossibleOverflows.
111 class CheckOverflowOps :
112 public EvaluatedExprVisitor<CheckOverflowOps> {
114 typedef SmallVectorImpl<MallocOverflowCheck> theVecType;
117 theVecType &toScanFor;
120 bool isIntZeroExpr(const Expr *E) const {
121 if (!E->getType()->isIntegralOrEnumerationType())
124 if (E->EvaluateAsInt(Result, Context))
129 void CheckExpr(const Expr *E_p) {
130 const Expr *E = E_p->IgnoreParenImpCasts();
132 theVecType::iterator i = toScanFor.end();
133 theVecType::iterator e = toScanFor.begin();
135 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
136 const Decl * EdreD = DR->getDecl();
139 if (const DeclRefExpr *DR_i = dyn_cast<DeclRefExpr>(i->variable)) {
140 if (DR_i->getDecl() == EdreD)
141 i = toScanFor.erase(i);
145 else if (isa<MemberExpr>(E)) {
146 // No points-to analysis, just look at the member
147 const Decl * EmeMD = dyn_cast<MemberExpr>(E)->getMemberDecl();
150 if (isa<MemberExpr>(i->variable)) {
151 if (dyn_cast<MemberExpr>(i->variable)->getMemberDecl() == EmeMD)
152 i = toScanFor.erase (i);
159 void VisitBinaryOperator(BinaryOperator *E) {
160 if (E->isComparisonOp()) {
161 const Expr * lhs = E->getLHS();
162 const Expr * rhs = E->getRHS();
163 // Ignore comparisons against zero, since they generally don't
164 // protect against an overflow.
165 if (!isIntZeroExpr(lhs) && ! isIntZeroExpr(rhs)) {
170 EvaluatedExprVisitor<CheckOverflowOps>::VisitBinaryOperator(E);
173 /* We specifically ignore loop conditions, because they're typically
175 void VisitWhileStmt(WhileStmt *S) {
176 return this->Visit(S->getBody());
178 void VisitForStmt(ForStmt *S) {
179 return this->Visit(S->getBody());
181 void VisitDoStmt(DoStmt *S) {
182 return this->Visit(S->getBody());
185 CheckOverflowOps(theVecType &v, ASTContext &ctx)
186 : EvaluatedExprVisitor<CheckOverflowOps>(ctx),
187 toScanFor(v), Context(ctx)
192 // OutputPossibleOverflows - We've found a possible overflow earlier,
193 // now check whether Body might contain a comparison which might be
194 // preventing the overflow.
195 // This doesn't do flow analysis, range analysis, or points-to analysis; it's
196 // just a dumb "is there a comparison" scan. The aim here is to
197 // detect the most blatent cases of overflow and educate the
199 void MallocOverflowSecurityChecker::OutputPossibleOverflows(
200 SmallVectorImpl<MallocOverflowCheck> &PossibleMallocOverflows,
201 const Decl *D, BugReporter &BR, AnalysisManager &mgr) const {
202 // By far the most common case: nothing to check.
203 if (PossibleMallocOverflows.empty())
206 // Delete any possible overflows which have a comparison.
207 CheckOverflowOps c(PossibleMallocOverflows, BR.getContext());
208 c.Visit(mgr.getAnalysisDeclContext(D)->getBody());
210 // Output warnings for all overflows that are left.
211 for (CheckOverflowOps::theVecType::iterator
212 i = PossibleMallocOverflows.begin(),
213 e = PossibleMallocOverflows.end();
216 SourceRange R = i->mulop->getSourceRange();
217 BR.EmitBasicReport(D, "malloc() size overflow", categories::UnixAPI,
218 "the computation of the size of the memory allocation may overflow",
219 PathDiagnosticLocation::createOperatorLoc(i->mulop,
220 BR.getSourceManager()), &R, 1);
224 void MallocOverflowSecurityChecker::checkASTCodeBody(const Decl *D,
225 AnalysisManager &mgr,
226 BugReporter &BR) const {
228 CFG *cfg = mgr.getCFG(D);
232 // A list of variables referenced in possibly overflowing malloc operands.
233 SmallVector<MallocOverflowCheck, 2> PossibleMallocOverflows;
235 for (CFG::iterator it = cfg->begin(), ei = cfg->end(); it != ei; ++it) {
236 CFGBlock *block = *it;
237 for (CFGBlock::iterator bi = block->begin(), be = block->end();
239 if (Optional<CFGStmt> CS = bi->getAs<CFGStmt>()) {
240 if (const CallExpr *TheCall = dyn_cast<CallExpr>(CS->getStmt())) {
242 const FunctionDecl *FD = TheCall->getDirectCallee();
247 // Get the name of the callee. If it's a builtin, strip off the prefix.
248 IdentifierInfo *FnInfo = FD->getIdentifier();
252 if (FnInfo->isStr ("malloc") || FnInfo->isStr ("_MALLOC")) {
253 if (TheCall->getNumArgs() == 1)
254 CheckMallocArgument(PossibleMallocOverflows, TheCall->getArg(0),
255 mgr.getASTContext());
262 OutputPossibleOverflows(PossibleMallocOverflows, D, BR, mgr);
265 void ento::registerMallocOverflowSecurityChecker(CheckerManager &mgr) {
266 mgr.registerChecker<MallocOverflowSecurityChecker>();