MallocOverflowSecurityChecker.cpp 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  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/PathSensitive/AnalysisManager.h"
  23. #include "clang/StaticAnalyzer/Core/Checker.h"
  24. #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.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. llvm::SmallVectorImpl<MallocOverflowCheck> &PossibleMallocOverflows,
  42. const Expr *TheArgument, ASTContext &Context) const;
  43. void OutputPossibleOverflows(
  44. llvm::SmallVectorImpl<MallocOverflowCheck> &PossibleMallocOverflows,
  45. const Decl *D, BugReporter &BR, AnalysisManager &mgr) const;
  46. };
  47. } // end anonymous namespace
  48. void MallocOverflowSecurityChecker::CheckMallocArgument(
  49. llvm::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 = NULL;
  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 == NULL && 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 == NULL)
  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 llvm::SmallVectorImpl<MallocOverflowCheck> theVecType;
  99. private:
  100. theVecType &toScanFor;
  101. ASTContext &Context;
  102. bool isIntZeroExpr(const Expr *E) const {
  103. return (E->getType()->isIntegralOrEnumerationType()
  104. && E->isEvaluatable(Context)
  105. && E->EvaluateAsInt(Context) == 0);
  106. }
  107. void CheckExpr(const Expr *E_p) {
  108. const Expr *E = E_p->IgnoreParenImpCasts();
  109. theVecType::iterator i = toScanFor.end();
  110. theVecType::iterator e = toScanFor.begin();
  111. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
  112. const Decl * EdreD = DR->getDecl();
  113. while (i != e) {
  114. --i;
  115. if (const DeclRefExpr *DR_i = dyn_cast<DeclRefExpr>(i->variable)) {
  116. if (DR_i->getDecl() == EdreD)
  117. i = toScanFor.erase(i);
  118. }
  119. }
  120. }
  121. else if (isa<MemberExpr>(E)) {
  122. // No points-to analysis, just look at the member
  123. const Decl * EmeMD = dyn_cast<MemberExpr>(E)->getMemberDecl();
  124. while (i != e) {
  125. --i;
  126. if (isa<MemberExpr>(i->variable)) {
  127. if (dyn_cast<MemberExpr>(i->variable)->getMemberDecl() == EmeMD)
  128. i = toScanFor.erase (i);
  129. }
  130. }
  131. }
  132. }
  133. public:
  134. void VisitBinaryOperator(BinaryOperator *E) {
  135. if (E->isComparisonOp()) {
  136. const Expr * lhs = E->getLHS();
  137. const Expr * rhs = E->getRHS();
  138. // Ignore comparisons against zero, since they generally don't
  139. // protect against an overflow.
  140. if (!isIntZeroExpr(lhs) && ! isIntZeroExpr(rhs)) {
  141. CheckExpr(lhs);
  142. CheckExpr(rhs);
  143. }
  144. }
  145. EvaluatedExprVisitor<CheckOverflowOps>::VisitBinaryOperator(E);
  146. }
  147. /* We specifically ignore loop conditions, because they're typically
  148. not error checks. */
  149. void VisitWhileStmt(WhileStmt *S) {
  150. return this->Visit(S->getBody());
  151. }
  152. void VisitForStmt(ForStmt *S) {
  153. return this->Visit(S->getBody());
  154. }
  155. void VisitDoStmt(DoStmt *S) {
  156. return this->Visit(S->getBody());
  157. }
  158. CheckOverflowOps(theVecType &v, ASTContext &ctx)
  159. : EvaluatedExprVisitor<CheckOverflowOps>(ctx),
  160. toScanFor(v), Context(ctx)
  161. { }
  162. };
  163. }
  164. // OutputPossibleOverflows - We've found a possible overflow earlier,
  165. // now check whether Body might contain a comparison which might be
  166. // preventing the overflow.
  167. // This doesn't do flow analysis, range analysis, or points-to analysis; it's
  168. // just a dumb "is there a comparison" scan. The aim here is to
  169. // detect the most blatent cases of overflow and educate the
  170. // programmer.
  171. void MallocOverflowSecurityChecker::OutputPossibleOverflows(
  172. llvm::SmallVectorImpl<MallocOverflowCheck> &PossibleMallocOverflows,
  173. const Decl *D, BugReporter &BR, AnalysisManager &mgr) const {
  174. // By far the most common case: nothing to check.
  175. if (PossibleMallocOverflows.empty())
  176. return;
  177. // Delete any possible overflows which have a comparison.
  178. CheckOverflowOps c(PossibleMallocOverflows, BR.getContext());
  179. c.Visit(mgr.getAnalysisContext(D)->getBody());
  180. // Output warnings for all overflows that are left.
  181. for (CheckOverflowOps::theVecType::iterator
  182. i = PossibleMallocOverflows.begin(),
  183. e = PossibleMallocOverflows.end();
  184. i != e;
  185. ++i) {
  186. SourceRange R = i->mulop->getSourceRange();
  187. BR.EmitBasicReport("MallocOverflowSecurityChecker",
  188. "the computation of the size of the memory allocation may overflow",
  189. PathDiagnosticLocation::createOperatorLoc(i->mulop,
  190. BR.getSourceManager()),
  191. &R, 1);
  192. }
  193. }
  194. void MallocOverflowSecurityChecker::checkASTCodeBody(const Decl *D,
  195. AnalysisManager &mgr,
  196. BugReporter &BR) const {
  197. CFG *cfg = mgr.getCFG(D);
  198. if (!cfg)
  199. return;
  200. // A list of variables referenced in possibly overflowing malloc operands.
  201. llvm::SmallVector<MallocOverflowCheck, 2> PossibleMallocOverflows;
  202. for (CFG::iterator it = cfg->begin(), ei = cfg->end(); it != ei; ++it) {
  203. CFGBlock *block = *it;
  204. for (CFGBlock::iterator bi = block->begin(), be = block->end();
  205. bi != be; ++bi) {
  206. if (const CFGStmt *CS = bi->getAs<CFGStmt>()) {
  207. if (const CallExpr *TheCall = dyn_cast<CallExpr>(CS->getStmt())) {
  208. // Get the callee.
  209. const FunctionDecl *FD = TheCall->getDirectCallee();
  210. if (!FD)
  211. return;
  212. // Get the name of the callee. If it's a builtin, strip off the prefix.
  213. IdentifierInfo *FnInfo = FD->getIdentifier();
  214. if (FnInfo->isStr ("malloc") || FnInfo->isStr ("_MALLOC")) {
  215. if (TheCall->getNumArgs() == 1)
  216. CheckMallocArgument(PossibleMallocOverflows, TheCall->getArg(0),
  217. mgr.getASTContext());
  218. }
  219. }
  220. }
  221. }
  222. }
  223. OutputPossibleOverflows(PossibleMallocOverflows, D, BR, mgr);
  224. }
  225. void ento::registerMallocOverflowSecurityChecker(CheckerManager &mgr) {
  226. mgr.registerChecker<MallocOverflowSecurityChecker>();
  227. }