MallocOverflowSecurityChecker.cpp 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  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. #include "ClangSACheckers.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/SmallVector.h"
  26. using namespace clang;
  27. using namespace ento;
  28. namespace {
  29. struct MallocOverflowCheck {
  30. const BinaryOperator *mulop;
  31. const Expr *variable;
  32. MallocOverflowCheck (const BinaryOperator *m, const Expr *v)
  33. : mulop(m), variable (v)
  34. {}
  35. };
  36. class MallocOverflowSecurityChecker : public Checker<check::ASTCodeBody> {
  37. public:
  38. void checkASTCodeBody(const Decl *D, AnalysisManager &mgr,
  39. BugReporter &BR) const;
  40. void CheckMallocArgument(
  41. SmallVectorImpl<MallocOverflowCheck> &PossibleMallocOverflows,
  42. const Expr *TheArgument, ASTContext &Context) const;
  43. void OutputPossibleOverflows(
  44. SmallVectorImpl<MallocOverflowCheck> &PossibleMallocOverflows,
  45. const Decl *D, BugReporter &BR, AnalysisManager &mgr) const;
  46. };
  47. } // end anonymous namespace
  48. void MallocOverflowSecurityChecker::CheckMallocArgument(
  49. SmallVectorImpl<MallocOverflowCheck> &PossibleMallocOverflows,
  50. const Expr *TheArgument,
  51. ASTContext &Context) const {
  52. /* Look for a linear combination with a single variable, and at least
  53. one multiplication.
  54. Reject anything that applies to the variable: an explicit cast,
  55. conditional expression, an operation that could reduce the range
  56. of the result, or anything too complicated :-). */
  57. const Expr * e = TheArgument;
  58. const BinaryOperator * mulop = nullptr;
  59. for (;;) {
  60. e = e->IgnoreParenImpCasts();
  61. if (isa<BinaryOperator>(e)) {
  62. const BinaryOperator * binop = dyn_cast<BinaryOperator>(e);
  63. BinaryOperatorKind opc = binop->getOpcode();
  64. // TODO: ignore multiplications by 1, reject if multiplied by 0.
  65. if (mulop == nullptr && opc == BO_Mul)
  66. mulop = binop;
  67. if (opc != BO_Mul && opc != BO_Add && opc != BO_Sub && opc != BO_Shl)
  68. return;
  69. const Expr *lhs = binop->getLHS();
  70. const Expr *rhs = binop->getRHS();
  71. if (rhs->isEvaluatable(Context))
  72. e = lhs;
  73. else if ((opc == BO_Add || opc == BO_Mul)
  74. && lhs->isEvaluatable(Context))
  75. e = rhs;
  76. else
  77. return;
  78. }
  79. else if (isa<DeclRefExpr>(e) || isa<MemberExpr>(e))
  80. break;
  81. else
  82. return;
  83. }
  84. if (mulop == nullptr)
  85. return;
  86. // We've found the right structure of malloc argument, now save
  87. // the data so when the body of the function is completely available
  88. // we can check for comparisons.
  89. // TODO: Could push this into the innermost scope where 'e' is
  90. // defined, rather than the whole function.
  91. PossibleMallocOverflows.push_back(MallocOverflowCheck(mulop, e));
  92. }
  93. namespace {
  94. // A worker class for OutputPossibleOverflows.
  95. class CheckOverflowOps :
  96. public EvaluatedExprVisitor<CheckOverflowOps> {
  97. public:
  98. typedef SmallVectorImpl<MallocOverflowCheck> theVecType;
  99. private:
  100. theVecType &toScanFor;
  101. ASTContext &Context;
  102. bool isIntZeroExpr(const Expr *E) const {
  103. if (!E->getType()->isIntegralOrEnumerationType())
  104. return false;
  105. llvm::APSInt Result;
  106. if (E->EvaluateAsInt(Result, Context))
  107. return Result == 0;
  108. return false;
  109. }
  110. void CheckExpr(const Expr *E_p) {
  111. const Expr *E = E_p->IgnoreParenImpCasts();
  112. theVecType::iterator i = toScanFor.end();
  113. theVecType::iterator e = toScanFor.begin();
  114. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
  115. const Decl * EdreD = DR->getDecl();
  116. while (i != e) {
  117. --i;
  118. if (const DeclRefExpr *DR_i = dyn_cast<DeclRefExpr>(i->variable)) {
  119. if (DR_i->getDecl() == EdreD)
  120. i = toScanFor.erase(i);
  121. }
  122. }
  123. }
  124. else if (const auto *ME = dyn_cast<MemberExpr>(E)) {
  125. // No points-to analysis, just look at the member
  126. const Decl *EmeMD = ME->getMemberDecl();
  127. while (i != e) {
  128. --i;
  129. if (const auto *ME_i = dyn_cast<MemberExpr>(i->variable)) {
  130. if (ME_i->getMemberDecl() == EmeMD)
  131. i = toScanFor.erase (i);
  132. }
  133. }
  134. }
  135. }
  136. public:
  137. void VisitBinaryOperator(BinaryOperator *E) {
  138. if (E->isComparisonOp()) {
  139. const Expr * lhs = E->getLHS();
  140. const Expr * rhs = E->getRHS();
  141. // Ignore comparisons against zero, since they generally don't
  142. // protect against an overflow.
  143. if (!isIntZeroExpr(lhs) && ! isIntZeroExpr(rhs)) {
  144. CheckExpr(lhs);
  145. CheckExpr(rhs);
  146. }
  147. }
  148. EvaluatedExprVisitor<CheckOverflowOps>::VisitBinaryOperator(E);
  149. }
  150. /* We specifically ignore loop conditions, because they're typically
  151. not error checks. */
  152. void VisitWhileStmt(WhileStmt *S) {
  153. return this->Visit(S->getBody());
  154. }
  155. void VisitForStmt(ForStmt *S) {
  156. return this->Visit(S->getBody());
  157. }
  158. void VisitDoStmt(DoStmt *S) {
  159. return this->Visit(S->getBody());
  160. }
  161. CheckOverflowOps(theVecType &v, ASTContext &ctx)
  162. : EvaluatedExprVisitor<CheckOverflowOps>(ctx),
  163. toScanFor(v), Context(ctx)
  164. { }
  165. };
  166. }
  167. // OutputPossibleOverflows - We've found a possible overflow earlier,
  168. // now check whether Body might contain a comparison which might be
  169. // preventing the overflow.
  170. // This doesn't do flow analysis, range analysis, or points-to analysis; it's
  171. // just a dumb "is there a comparison" scan. The aim here is to
  172. // detect the most blatent cases of overflow and educate the
  173. // programmer.
  174. void MallocOverflowSecurityChecker::OutputPossibleOverflows(
  175. SmallVectorImpl<MallocOverflowCheck> &PossibleMallocOverflows,
  176. const Decl *D, BugReporter &BR, AnalysisManager &mgr) const {
  177. // By far the most common case: nothing to check.
  178. if (PossibleMallocOverflows.empty())
  179. return;
  180. // Delete any possible overflows which have a comparison.
  181. CheckOverflowOps c(PossibleMallocOverflows, BR.getContext());
  182. c.Visit(mgr.getAnalysisDeclContext(D)->getBody());
  183. // Output warnings for all overflows that are left.
  184. for (CheckOverflowOps::theVecType::iterator
  185. i = PossibleMallocOverflows.begin(),
  186. e = PossibleMallocOverflows.end();
  187. i != e;
  188. ++i) {
  189. BR.EmitBasicReport(
  190. D, this, "malloc() size overflow", categories::UnixAPI,
  191. "the computation of the size of the memory allocation may overflow",
  192. PathDiagnosticLocation::createOperatorLoc(i->mulop,
  193. BR.getSourceManager()),
  194. i->mulop->getSourceRange());
  195. }
  196. }
  197. void MallocOverflowSecurityChecker::checkASTCodeBody(const Decl *D,
  198. AnalysisManager &mgr,
  199. BugReporter &BR) const {
  200. CFG *cfg = mgr.getCFG(D);
  201. if (!cfg)
  202. return;
  203. // A list of variables referenced in possibly overflowing malloc operands.
  204. SmallVector<MallocOverflowCheck, 2> PossibleMallocOverflows;
  205. for (CFG::iterator it = cfg->begin(), ei = cfg->end(); it != ei; ++it) {
  206. CFGBlock *block = *it;
  207. for (CFGBlock::iterator bi = block->begin(), be = block->end();
  208. bi != be; ++bi) {
  209. if (Optional<CFGStmt> CS = bi->getAs<CFGStmt>()) {
  210. if (const CallExpr *TheCall = dyn_cast<CallExpr>(CS->getStmt())) {
  211. // Get the callee.
  212. const FunctionDecl *FD = TheCall->getDirectCallee();
  213. if (!FD)
  214. return;
  215. // Get the name of the callee. If it's a builtin, strip off the prefix.
  216. IdentifierInfo *FnInfo = FD->getIdentifier();
  217. if (!FnInfo)
  218. return;
  219. if (FnInfo->isStr ("malloc") || FnInfo->isStr ("_MALLOC")) {
  220. if (TheCall->getNumArgs() == 1)
  221. CheckMallocArgument(PossibleMallocOverflows, TheCall->getArg(0),
  222. mgr.getASTContext());
  223. }
  224. }
  225. }
  226. }
  227. }
  228. OutputPossibleOverflows(PossibleMallocOverflows, D, BR, mgr);
  229. }
  230. void
  231. ento::registerMallocOverflowSecurityChecker(CheckerManager &mgr) {
  232. mgr.registerChecker<MallocOverflowSecurityChecker>();
  233. }