GenericTaintChecker.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744
  1. //== GenericTaintChecker.cpp ----------------------------------- -*- 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 defines the attack surface for generic taint propagation.
  11. //
  12. // The taint information produced by it might be useful to other checkers. For
  13. // example, checkers should report errors which involve tainted data more
  14. // aggressively, even if the involved symbols are under constrained.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #include "ClangSACheckers.h"
  18. #include "clang/AST/Attr.h"
  19. #include "clang/Basic/Builtins.h"
  20. #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
  21. #include "clang/StaticAnalyzer/Core/Checker.h"
  22. #include "clang/StaticAnalyzer/Core/CheckerManager.h"
  23. #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
  24. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
  25. #include <climits>
  26. using namespace clang;
  27. using namespace ento;
  28. namespace {
  29. class GenericTaintChecker : public Checker< check::PostStmt<CallExpr>,
  30. check::PreStmt<CallExpr> > {
  31. public:
  32. static void *getTag() { static int Tag; return &Tag; }
  33. void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
  34. void checkPostStmt(const DeclRefExpr *DRE, CheckerContext &C) const;
  35. void checkPreStmt(const CallExpr *CE, CheckerContext &C) const;
  36. private:
  37. static const unsigned InvalidArgIndex = UINT_MAX;
  38. /// Denotes the return vale.
  39. static const unsigned ReturnValueIndex = UINT_MAX - 1;
  40. mutable OwningPtr<BugType> BT;
  41. inline void initBugType() const {
  42. if (!BT)
  43. BT.reset(new BugType("Use of Untrusted Data", "Untrusted Data"));
  44. }
  45. /// \brief Catch taint related bugs. Check if tainted data is passed to a
  46. /// system call etc.
  47. bool checkPre(const CallExpr *CE, CheckerContext &C) const;
  48. /// \brief Add taint sources on a pre-visit.
  49. void addSourcesPre(const CallExpr *CE, CheckerContext &C) const;
  50. /// \brief Propagate taint generated at pre-visit.
  51. bool propagateFromPre(const CallExpr *CE, CheckerContext &C) const;
  52. /// \brief Add taint sources on a post visit.
  53. void addSourcesPost(const CallExpr *CE, CheckerContext &C) const;
  54. /// Check if the region the expression evaluates to is the standard input,
  55. /// and thus, is tainted.
  56. static bool isStdin(const Expr *E, CheckerContext &C);
  57. /// \brief Given a pointer argument, get the symbol of the value it contains
  58. /// (points to).
  59. static SymbolRef getPointedToSymbol(CheckerContext &C, const Expr *Arg);
  60. /// Functions defining the attack surface.
  61. typedef ProgramStateRef (GenericTaintChecker::*FnCheck)(const CallExpr *,
  62. CheckerContext &C) const;
  63. ProgramStateRef postScanf(const CallExpr *CE, CheckerContext &C) const;
  64. ProgramStateRef postSocket(const CallExpr *CE, CheckerContext &C) const;
  65. ProgramStateRef postRetTaint(const CallExpr *CE, CheckerContext &C) const;
  66. /// Taint the scanned input if the file is tainted.
  67. ProgramStateRef preFscanf(const CallExpr *CE, CheckerContext &C) const;
  68. /// Check for CWE-134: Uncontrolled Format String.
  69. static const char MsgUncontrolledFormatString[];
  70. bool checkUncontrolledFormatString(const CallExpr *CE,
  71. CheckerContext &C) const;
  72. /// Check for:
  73. /// CERT/STR02-C. "Sanitize data passed to complex subsystems"
  74. /// CWE-78, "Failure to Sanitize Data into an OS Command"
  75. static const char MsgSanitizeSystemArgs[];
  76. bool checkSystemCall(const CallExpr *CE, StringRef Name,
  77. CheckerContext &C) const;
  78. /// Check if tainted data is used as a buffer size ins strn.. functions,
  79. /// and allocators.
  80. static const char MsgTaintedBufferSize[];
  81. bool checkTaintedBufferSize(const CallExpr *CE, const FunctionDecl *FDecl,
  82. CheckerContext &C) const;
  83. /// Generate a report if the expression is tainted or points to tainted data.
  84. bool generateReportIfTainted(const Expr *E, const char Msg[],
  85. CheckerContext &C) const;
  86. typedef SmallVector<unsigned, 2> ArgVector;
  87. /// \brief A struct used to specify taint propagation rules for a function.
  88. ///
  89. /// If any of the possible taint source arguments is tainted, all of the
  90. /// destination arguments should also be tainted. Use InvalidArgIndex in the
  91. /// src list to specify that all of the arguments can introduce taint. Use
  92. /// InvalidArgIndex in the dst arguments to signify that all the non-const
  93. /// pointer and reference arguments might be tainted on return. If
  94. /// ReturnValueIndex is added to the dst list, the return value will be
  95. /// tainted.
  96. struct TaintPropagationRule {
  97. /// List of arguments which can be taint sources and should be checked.
  98. ArgVector SrcArgs;
  99. /// List of arguments which should be tainted on function return.
  100. ArgVector DstArgs;
  101. // TODO: Check if using other data structures would be more optimal.
  102. TaintPropagationRule() {}
  103. TaintPropagationRule(unsigned SArg,
  104. unsigned DArg, bool TaintRet = false) {
  105. SrcArgs.push_back(SArg);
  106. DstArgs.push_back(DArg);
  107. if (TaintRet)
  108. DstArgs.push_back(ReturnValueIndex);
  109. }
  110. TaintPropagationRule(unsigned SArg1, unsigned SArg2,
  111. unsigned DArg, bool TaintRet = false) {
  112. SrcArgs.push_back(SArg1);
  113. SrcArgs.push_back(SArg2);
  114. DstArgs.push_back(DArg);
  115. if (TaintRet)
  116. DstArgs.push_back(ReturnValueIndex);
  117. }
  118. /// Get the propagation rule for a given function.
  119. static TaintPropagationRule
  120. getTaintPropagationRule(const FunctionDecl *FDecl,
  121. StringRef Name,
  122. CheckerContext &C);
  123. inline void addSrcArg(unsigned A) { SrcArgs.push_back(A); }
  124. inline void addDstArg(unsigned A) { DstArgs.push_back(A); }
  125. inline bool isNull() const { return SrcArgs.empty(); }
  126. inline bool isDestinationArgument(unsigned ArgNum) const {
  127. return (std::find(DstArgs.begin(),
  128. DstArgs.end(), ArgNum) != DstArgs.end());
  129. }
  130. static inline bool isTaintedOrPointsToTainted(const Expr *E,
  131. ProgramStateRef State,
  132. CheckerContext &C) {
  133. return (State->isTainted(E, C.getLocationContext()) || isStdin(E, C) ||
  134. (E->getType().getTypePtr()->isPointerType() &&
  135. State->isTainted(getPointedToSymbol(C, E))));
  136. }
  137. /// \brief Pre-process a function which propagates taint according to the
  138. /// taint rule.
  139. ProgramStateRef process(const CallExpr *CE, CheckerContext &C) const;
  140. };
  141. };
  142. const unsigned GenericTaintChecker::ReturnValueIndex;
  143. const unsigned GenericTaintChecker::InvalidArgIndex;
  144. const char GenericTaintChecker::MsgUncontrolledFormatString[] =
  145. "Untrusted data is used as a format string "
  146. "(CWE-134: Uncontrolled Format String)";
  147. const char GenericTaintChecker::MsgSanitizeSystemArgs[] =
  148. "Untrusted data is passed to a system call "
  149. "(CERT/STR02-C. Sanitize data passed to complex subsystems)";
  150. const char GenericTaintChecker::MsgTaintedBufferSize[] =
  151. "Untrusted data is used to specify the buffer size "
  152. "(CERT/STR31-C. Guarantee that storage for strings has sufficient space for "
  153. "character data and the null terminator)";
  154. } // end of anonymous namespace
  155. /// A set which is used to pass information from call pre-visit instruction
  156. /// to the call post-visit. The values are unsigned integers, which are either
  157. /// ReturnValueIndex, or indexes of the pointer/reference argument, which
  158. /// points to data, which should be tainted on return.
  159. REGISTER_SET_WITH_PROGRAMSTATE(TaintArgsOnPostVisit, unsigned)
  160. GenericTaintChecker::TaintPropagationRule
  161. GenericTaintChecker::TaintPropagationRule::getTaintPropagationRule(
  162. const FunctionDecl *FDecl,
  163. StringRef Name,
  164. CheckerContext &C) {
  165. // TODO: Currently, we might loose precision here: we always mark a return
  166. // value as tainted even if it's just a pointer, pointing to tainted data.
  167. // Check for exact name match for functions without builtin substitutes.
  168. TaintPropagationRule Rule = llvm::StringSwitch<TaintPropagationRule>(Name)
  169. .Case("atoi", TaintPropagationRule(0, ReturnValueIndex))
  170. .Case("atol", TaintPropagationRule(0, ReturnValueIndex))
  171. .Case("atoll", TaintPropagationRule(0, ReturnValueIndex))
  172. .Case("getc", TaintPropagationRule(0, ReturnValueIndex))
  173. .Case("fgetc", TaintPropagationRule(0, ReturnValueIndex))
  174. .Case("getc_unlocked", TaintPropagationRule(0, ReturnValueIndex))
  175. .Case("getw", TaintPropagationRule(0, ReturnValueIndex))
  176. .Case("toupper", TaintPropagationRule(0, ReturnValueIndex))
  177. .Case("tolower", TaintPropagationRule(0, ReturnValueIndex))
  178. .Case("strchr", TaintPropagationRule(0, ReturnValueIndex))
  179. .Case("strrchr", TaintPropagationRule(0, ReturnValueIndex))
  180. .Case("read", TaintPropagationRule(0, 2, 1, true))
  181. .Case("pread", TaintPropagationRule(InvalidArgIndex, 1, true))
  182. .Case("gets", TaintPropagationRule(InvalidArgIndex, 0, true))
  183. .Case("fgets", TaintPropagationRule(2, 0, true))
  184. .Case("getline", TaintPropagationRule(2, 0))
  185. .Case("getdelim", TaintPropagationRule(3, 0))
  186. .Case("fgetln", TaintPropagationRule(0, ReturnValueIndex))
  187. .Default(TaintPropagationRule());
  188. if (!Rule.isNull())
  189. return Rule;
  190. // Check if it's one of the memory setting/copying functions.
  191. // This check is specialized but faster then calling isCLibraryFunction.
  192. unsigned BId = 0;
  193. if ( (BId = FDecl->getMemoryFunctionKind()) )
  194. switch(BId) {
  195. case Builtin::BImemcpy:
  196. case Builtin::BImemmove:
  197. case Builtin::BIstrncpy:
  198. case Builtin::BIstrncat:
  199. return TaintPropagationRule(1, 2, 0, true);
  200. case Builtin::BIstrlcpy:
  201. case Builtin::BIstrlcat:
  202. return TaintPropagationRule(1, 2, 0, false);
  203. case Builtin::BIstrndup:
  204. return TaintPropagationRule(0, 1, ReturnValueIndex);
  205. default:
  206. break;
  207. };
  208. // Process all other functions which could be defined as builtins.
  209. if (Rule.isNull()) {
  210. if (C.isCLibraryFunction(FDecl, "snprintf") ||
  211. C.isCLibraryFunction(FDecl, "sprintf"))
  212. return TaintPropagationRule(InvalidArgIndex, 0, true);
  213. else if (C.isCLibraryFunction(FDecl, "strcpy") ||
  214. C.isCLibraryFunction(FDecl, "stpcpy") ||
  215. C.isCLibraryFunction(FDecl, "strcat"))
  216. return TaintPropagationRule(1, 0, true);
  217. else if (C.isCLibraryFunction(FDecl, "bcopy"))
  218. return TaintPropagationRule(0, 2, 1, false);
  219. else if (C.isCLibraryFunction(FDecl, "strdup") ||
  220. C.isCLibraryFunction(FDecl, "strdupa"))
  221. return TaintPropagationRule(0, ReturnValueIndex);
  222. else if (C.isCLibraryFunction(FDecl, "wcsdup"))
  223. return TaintPropagationRule(0, ReturnValueIndex);
  224. }
  225. // Skipping the following functions, since they might be used for cleansing
  226. // or smart memory copy:
  227. // - memccpy - copying until hitting a special character.
  228. return TaintPropagationRule();
  229. }
  230. void GenericTaintChecker::checkPreStmt(const CallExpr *CE,
  231. CheckerContext &C) const {
  232. // Check for errors first.
  233. if (checkPre(CE, C))
  234. return;
  235. // Add taint second.
  236. addSourcesPre(CE, C);
  237. }
  238. void GenericTaintChecker::checkPostStmt(const CallExpr *CE,
  239. CheckerContext &C) const {
  240. if (propagateFromPre(CE, C))
  241. return;
  242. addSourcesPost(CE, C);
  243. }
  244. void GenericTaintChecker::addSourcesPre(const CallExpr *CE,
  245. CheckerContext &C) const {
  246. ProgramStateRef State = 0;
  247. const FunctionDecl *FDecl = C.getCalleeDecl(CE);
  248. if (!FDecl || FDecl->getKind() != Decl::Function)
  249. return;
  250. StringRef Name = C.getCalleeName(FDecl);
  251. if (Name.empty())
  252. return;
  253. // First, try generating a propagation rule for this function.
  254. TaintPropagationRule Rule =
  255. TaintPropagationRule::getTaintPropagationRule(FDecl, Name, C);
  256. if (!Rule.isNull()) {
  257. State = Rule.process(CE, C);
  258. if (!State)
  259. return;
  260. C.addTransition(State);
  261. return;
  262. }
  263. // Otherwise, check if we have custom pre-processing implemented.
  264. FnCheck evalFunction = llvm::StringSwitch<FnCheck>(Name)
  265. .Case("fscanf", &GenericTaintChecker::preFscanf)
  266. .Default(0);
  267. // Check and evaluate the call.
  268. if (evalFunction)
  269. State = (this->*evalFunction)(CE, C);
  270. if (!State)
  271. return;
  272. C.addTransition(State);
  273. }
  274. bool GenericTaintChecker::propagateFromPre(const CallExpr *CE,
  275. CheckerContext &C) const {
  276. ProgramStateRef State = C.getState();
  277. // Depending on what was tainted at pre-visit, we determined a set of
  278. // arguments which should be tainted after the function returns. These are
  279. // stored in the state as TaintArgsOnPostVisit set.
  280. TaintArgsOnPostVisitTy TaintArgs = State->get<TaintArgsOnPostVisit>();
  281. if (TaintArgs.isEmpty())
  282. return false;
  283. for (llvm::ImmutableSet<unsigned>::iterator
  284. I = TaintArgs.begin(), E = TaintArgs.end(); I != E; ++I) {
  285. unsigned ArgNum = *I;
  286. // Special handling for the tainted return value.
  287. if (ArgNum == ReturnValueIndex) {
  288. State = State->addTaint(CE, C.getLocationContext());
  289. continue;
  290. }
  291. // The arguments are pointer arguments. The data they are pointing at is
  292. // tainted after the call.
  293. if (CE->getNumArgs() < (ArgNum + 1))
  294. return false;
  295. const Expr* Arg = CE->getArg(ArgNum);
  296. SymbolRef Sym = getPointedToSymbol(C, Arg);
  297. if (Sym)
  298. State = State->addTaint(Sym);
  299. }
  300. // Clear up the taint info from the state.
  301. State = State->remove<TaintArgsOnPostVisit>();
  302. if (State != C.getState()) {
  303. C.addTransition(State);
  304. return true;
  305. }
  306. return false;
  307. }
  308. void GenericTaintChecker::addSourcesPost(const CallExpr *CE,
  309. CheckerContext &C) const {
  310. // Define the attack surface.
  311. // Set the evaluation function by switching on the callee name.
  312. const FunctionDecl *FDecl = C.getCalleeDecl(CE);
  313. if (!FDecl || FDecl->getKind() != Decl::Function)
  314. return;
  315. StringRef Name = C.getCalleeName(FDecl);
  316. if (Name.empty())
  317. return;
  318. FnCheck evalFunction = llvm::StringSwitch<FnCheck>(Name)
  319. .Case("scanf", &GenericTaintChecker::postScanf)
  320. // TODO: Add support for vfscanf & family.
  321. .Case("getchar", &GenericTaintChecker::postRetTaint)
  322. .Case("getchar_unlocked", &GenericTaintChecker::postRetTaint)
  323. .Case("getenv", &GenericTaintChecker::postRetTaint)
  324. .Case("fopen", &GenericTaintChecker::postRetTaint)
  325. .Case("fdopen", &GenericTaintChecker::postRetTaint)
  326. .Case("freopen", &GenericTaintChecker::postRetTaint)
  327. .Case("getch", &GenericTaintChecker::postRetTaint)
  328. .Case("wgetch", &GenericTaintChecker::postRetTaint)
  329. .Case("socket", &GenericTaintChecker::postSocket)
  330. .Default(0);
  331. // If the callee isn't defined, it is not of security concern.
  332. // Check and evaluate the call.
  333. ProgramStateRef State = 0;
  334. if (evalFunction)
  335. State = (this->*evalFunction)(CE, C);
  336. if (!State)
  337. return;
  338. C.addTransition(State);
  339. }
  340. bool GenericTaintChecker::checkPre(const CallExpr *CE, CheckerContext &C) const{
  341. if (checkUncontrolledFormatString(CE, C))
  342. return true;
  343. const FunctionDecl *FDecl = C.getCalleeDecl(CE);
  344. if (!FDecl || FDecl->getKind() != Decl::Function)
  345. return false;
  346. StringRef Name = C.getCalleeName(FDecl);
  347. if (Name.empty())
  348. return false;
  349. if (checkSystemCall(CE, Name, C))
  350. return true;
  351. if (checkTaintedBufferSize(CE, FDecl, C))
  352. return true;
  353. return false;
  354. }
  355. SymbolRef GenericTaintChecker::getPointedToSymbol(CheckerContext &C,
  356. const Expr* Arg) {
  357. ProgramStateRef State = C.getState();
  358. SVal AddrVal = State->getSVal(Arg->IgnoreParens(), C.getLocationContext());
  359. if (AddrVal.isUnknownOrUndef())
  360. return 0;
  361. Optional<Loc> AddrLoc = AddrVal.getAs<Loc>();
  362. if (!AddrLoc)
  363. return 0;
  364. const PointerType *ArgTy =
  365. dyn_cast<PointerType>(Arg->getType().getCanonicalType().getTypePtr());
  366. SVal Val = State->getSVal(*AddrLoc,
  367. ArgTy ? ArgTy->getPointeeType(): QualType());
  368. return Val.getAsSymbol();
  369. }
  370. ProgramStateRef
  371. GenericTaintChecker::TaintPropagationRule::process(const CallExpr *CE,
  372. CheckerContext &C) const {
  373. ProgramStateRef State = C.getState();
  374. // Check for taint in arguments.
  375. bool IsTainted = false;
  376. for (ArgVector::const_iterator I = SrcArgs.begin(),
  377. E = SrcArgs.end(); I != E; ++I) {
  378. unsigned ArgNum = *I;
  379. if (ArgNum == InvalidArgIndex) {
  380. // Check if any of the arguments is tainted, but skip the
  381. // destination arguments.
  382. for (unsigned int i = 0; i < CE->getNumArgs(); ++i) {
  383. if (isDestinationArgument(i))
  384. continue;
  385. if ((IsTainted = isTaintedOrPointsToTainted(CE->getArg(i), State, C)))
  386. break;
  387. }
  388. break;
  389. }
  390. if (CE->getNumArgs() < (ArgNum + 1))
  391. return State;
  392. if ((IsTainted = isTaintedOrPointsToTainted(CE->getArg(ArgNum), State, C)))
  393. break;
  394. }
  395. if (!IsTainted)
  396. return State;
  397. // Mark the arguments which should be tainted after the function returns.
  398. for (ArgVector::const_iterator I = DstArgs.begin(),
  399. E = DstArgs.end(); I != E; ++I) {
  400. unsigned ArgNum = *I;
  401. // Should we mark all arguments as tainted?
  402. if (ArgNum == InvalidArgIndex) {
  403. // For all pointer and references that were passed in:
  404. // If they are not pointing to const data, mark data as tainted.
  405. // TODO: So far we are just going one level down; ideally we'd need to
  406. // recurse here.
  407. for (unsigned int i = 0; i < CE->getNumArgs(); ++i) {
  408. const Expr *Arg = CE->getArg(i);
  409. // Process pointer argument.
  410. const Type *ArgTy = Arg->getType().getTypePtr();
  411. QualType PType = ArgTy->getPointeeType();
  412. if ((!PType.isNull() && !PType.isConstQualified())
  413. || (ArgTy->isReferenceType() && !Arg->getType().isConstQualified()))
  414. State = State->add<TaintArgsOnPostVisit>(i);
  415. }
  416. continue;
  417. }
  418. // Should mark the return value?
  419. if (ArgNum == ReturnValueIndex) {
  420. State = State->add<TaintArgsOnPostVisit>(ReturnValueIndex);
  421. continue;
  422. }
  423. // Mark the given argument.
  424. assert(ArgNum < CE->getNumArgs());
  425. State = State->add<TaintArgsOnPostVisit>(ArgNum);
  426. }
  427. return State;
  428. }
  429. // If argument 0 (file descriptor) is tainted, all arguments except for arg 0
  430. // and arg 1 should get taint.
  431. ProgramStateRef GenericTaintChecker::preFscanf(const CallExpr *CE,
  432. CheckerContext &C) const {
  433. assert(CE->getNumArgs() >= 2);
  434. ProgramStateRef State = C.getState();
  435. // Check is the file descriptor is tainted.
  436. if (State->isTainted(CE->getArg(0), C.getLocationContext()) ||
  437. isStdin(CE->getArg(0), C)) {
  438. // All arguments except for the first two should get taint.
  439. for (unsigned int i = 2; i < CE->getNumArgs(); ++i)
  440. State = State->add<TaintArgsOnPostVisit>(i);
  441. return State;
  442. }
  443. return 0;
  444. }
  445. // If argument 0(protocol domain) is network, the return value should get taint.
  446. ProgramStateRef GenericTaintChecker::postSocket(const CallExpr *CE,
  447. CheckerContext &C) const {
  448. ProgramStateRef State = C.getState();
  449. if (CE->getNumArgs() < 3)
  450. return State;
  451. SourceLocation DomLoc = CE->getArg(0)->getExprLoc();
  452. StringRef DomName = C.getMacroNameOrSpelling(DomLoc);
  453. // White list the internal communication protocols.
  454. if (DomName.equals("AF_SYSTEM") || DomName.equals("AF_LOCAL") ||
  455. DomName.equals("AF_UNIX") || DomName.equals("AF_RESERVED_36"))
  456. return State;
  457. State = State->addTaint(CE, C.getLocationContext());
  458. return State;
  459. }
  460. ProgramStateRef GenericTaintChecker::postScanf(const CallExpr *CE,
  461. CheckerContext &C) const {
  462. ProgramStateRef State = C.getState();
  463. if (CE->getNumArgs() < 2)
  464. return State;
  465. // All arguments except for the very first one should get taint.
  466. for (unsigned int i = 1; i < CE->getNumArgs(); ++i) {
  467. // The arguments are pointer arguments. The data they are pointing at is
  468. // tainted after the call.
  469. const Expr* Arg = CE->getArg(i);
  470. SymbolRef Sym = getPointedToSymbol(C, Arg);
  471. if (Sym)
  472. State = State->addTaint(Sym);
  473. }
  474. return State;
  475. }
  476. ProgramStateRef GenericTaintChecker::postRetTaint(const CallExpr *CE,
  477. CheckerContext &C) const {
  478. return C.getState()->addTaint(CE, C.getLocationContext());
  479. }
  480. bool GenericTaintChecker::isStdin(const Expr *E, CheckerContext &C) {
  481. ProgramStateRef State = C.getState();
  482. SVal Val = State->getSVal(E, C.getLocationContext());
  483. // stdin is a pointer, so it would be a region.
  484. const MemRegion *MemReg = Val.getAsRegion();
  485. // The region should be symbolic, we do not know it's value.
  486. const SymbolicRegion *SymReg = dyn_cast_or_null<SymbolicRegion>(MemReg);
  487. if (!SymReg)
  488. return false;
  489. // Get it's symbol and find the declaration region it's pointing to.
  490. const SymbolRegionValue *Sm =dyn_cast<SymbolRegionValue>(SymReg->getSymbol());
  491. if (!Sm)
  492. return false;
  493. const DeclRegion *DeclReg = dyn_cast_or_null<DeclRegion>(Sm->getRegion());
  494. if (!DeclReg)
  495. return false;
  496. // This region corresponds to a declaration, find out if it's a global/extern
  497. // variable named stdin with the proper type.
  498. if (const VarDecl *D = dyn_cast_or_null<VarDecl>(DeclReg->getDecl())) {
  499. D = D->getCanonicalDecl();
  500. if ((D->getName().find("stdin") != StringRef::npos) && D->isExternC())
  501. if (const PointerType * PtrTy =
  502. dyn_cast<PointerType>(D->getType().getTypePtr()))
  503. if (PtrTy->getPointeeType() == C.getASTContext().getFILEType())
  504. return true;
  505. }
  506. return false;
  507. }
  508. static bool getPrintfFormatArgumentNum(const CallExpr *CE,
  509. const CheckerContext &C,
  510. unsigned int &ArgNum) {
  511. // Find if the function contains a format string argument.
  512. // Handles: fprintf, printf, sprintf, snprintf, vfprintf, vprintf, vsprintf,
  513. // vsnprintf, syslog, custom annotated functions.
  514. const FunctionDecl *FDecl = C.getCalleeDecl(CE);
  515. if (!FDecl)
  516. return false;
  517. for (specific_attr_iterator<FormatAttr>
  518. i = FDecl->specific_attr_begin<FormatAttr>(),
  519. e = FDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) {
  520. const FormatAttr *Format = *i;
  521. ArgNum = Format->getFormatIdx() - 1;
  522. if ((Format->getType() == "printf") && CE->getNumArgs() > ArgNum)
  523. return true;
  524. }
  525. // Or if a function is named setproctitle (this is a heuristic).
  526. if (C.getCalleeName(CE).find("setproctitle") != StringRef::npos) {
  527. ArgNum = 0;
  528. return true;
  529. }
  530. return false;
  531. }
  532. bool GenericTaintChecker::generateReportIfTainted(const Expr *E,
  533. const char Msg[],
  534. CheckerContext &C) const {
  535. assert(E);
  536. // Check for taint.
  537. ProgramStateRef State = C.getState();
  538. if (!State->isTainted(getPointedToSymbol(C, E)) &&
  539. !State->isTainted(E, C.getLocationContext()))
  540. return false;
  541. // Generate diagnostic.
  542. if (ExplodedNode *N = C.addTransition()) {
  543. initBugType();
  544. BugReport *report = new BugReport(*BT, Msg, N);
  545. report->addRange(E->getSourceRange());
  546. C.emitReport(report);
  547. return true;
  548. }
  549. return false;
  550. }
  551. bool GenericTaintChecker::checkUncontrolledFormatString(const CallExpr *CE,
  552. CheckerContext &C) const{
  553. // Check if the function contains a format string argument.
  554. unsigned int ArgNum = 0;
  555. if (!getPrintfFormatArgumentNum(CE, C, ArgNum))
  556. return false;
  557. // If either the format string content or the pointer itself are tainted, warn.
  558. if (generateReportIfTainted(CE->getArg(ArgNum),
  559. MsgUncontrolledFormatString, C))
  560. return true;
  561. return false;
  562. }
  563. bool GenericTaintChecker::checkSystemCall(const CallExpr *CE,
  564. StringRef Name,
  565. CheckerContext &C) const {
  566. // TODO: It might make sense to run this check on demand. In some cases,
  567. // we should check if the environment has been cleansed here. We also might
  568. // need to know if the user was reset before these calls(seteuid).
  569. unsigned ArgNum = llvm::StringSwitch<unsigned>(Name)
  570. .Case("system", 0)
  571. .Case("popen", 0)
  572. .Case("execl", 0)
  573. .Case("execle", 0)
  574. .Case("execlp", 0)
  575. .Case("execv", 0)
  576. .Case("execvp", 0)
  577. .Case("execvP", 0)
  578. .Case("execve", 0)
  579. .Case("dlopen", 0)
  580. .Default(UINT_MAX);
  581. if (ArgNum == UINT_MAX || CE->getNumArgs() < (ArgNum + 1))
  582. return false;
  583. if (generateReportIfTainted(CE->getArg(ArgNum),
  584. MsgSanitizeSystemArgs, C))
  585. return true;
  586. return false;
  587. }
  588. // TODO: Should this check be a part of the CString checker?
  589. // If yes, should taint be a global setting?
  590. bool GenericTaintChecker::checkTaintedBufferSize(const CallExpr *CE,
  591. const FunctionDecl *FDecl,
  592. CheckerContext &C) const {
  593. // If the function has a buffer size argument, set ArgNum.
  594. unsigned ArgNum = InvalidArgIndex;
  595. unsigned BId = 0;
  596. if ( (BId = FDecl->getMemoryFunctionKind()) )
  597. switch(BId) {
  598. case Builtin::BImemcpy:
  599. case Builtin::BImemmove:
  600. case Builtin::BIstrncpy:
  601. ArgNum = 2;
  602. break;
  603. case Builtin::BIstrndup:
  604. ArgNum = 1;
  605. break;
  606. default:
  607. break;
  608. };
  609. if (ArgNum == InvalidArgIndex) {
  610. if (C.isCLibraryFunction(FDecl, "malloc") ||
  611. C.isCLibraryFunction(FDecl, "calloc") ||
  612. C.isCLibraryFunction(FDecl, "alloca"))
  613. ArgNum = 0;
  614. else if (C.isCLibraryFunction(FDecl, "memccpy"))
  615. ArgNum = 3;
  616. else if (C.isCLibraryFunction(FDecl, "realloc"))
  617. ArgNum = 1;
  618. else if (C.isCLibraryFunction(FDecl, "bcopy"))
  619. ArgNum = 2;
  620. }
  621. if (ArgNum != InvalidArgIndex && CE->getNumArgs() > ArgNum &&
  622. generateReportIfTainted(CE->getArg(ArgNum), MsgTaintedBufferSize, C))
  623. return true;
  624. return false;
  625. }
  626. void ento::registerGenericTaintChecker(CheckerManager &mgr) {
  627. mgr.registerChecker<GenericTaintChecker>();
  628. }