CheckSecuritySyntaxOnly.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787
  1. //==- CheckSecuritySyntaxOnly.cpp - Basic security checks --------*- 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 file defines a set of flow-insensitive security checks.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "ClangSACheckers.h"
  14. #include "clang/Analysis/AnalysisContext.h"
  15. #include "clang/AST/StmtVisitor.h"
  16. #include "clang/Basic/TargetInfo.h"
  17. #include "clang/StaticAnalyzer/Core/Checker.h"
  18. #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
  19. #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
  20. #include "llvm/ADT/SmallString.h"
  21. #include "llvm/ADT/StringSwitch.h"
  22. #include "llvm/Support/raw_ostream.h"
  23. using namespace clang;
  24. using namespace ento;
  25. static bool isArc4RandomAvailable(const ASTContext &Ctx) {
  26. const llvm::Triple &T = Ctx.getTargetInfo().getTriple();
  27. return T.getVendor() == llvm::Triple::Apple ||
  28. T.getOS() == llvm::Triple::FreeBSD ||
  29. T.getOS() == llvm::Triple::NetBSD ||
  30. T.getOS() == llvm::Triple::OpenBSD ||
  31. T.getOS() == llvm::Triple::Bitrig ||
  32. T.getOS() == llvm::Triple::DragonFly;
  33. }
  34. namespace {
  35. struct DefaultBool {
  36. bool val;
  37. DefaultBool() : val(false) {}
  38. operator bool() const { return val; }
  39. DefaultBool &operator=(bool b) { val = b; return *this; }
  40. };
  41. struct ChecksFilter {
  42. DefaultBool check_gets;
  43. DefaultBool check_getpw;
  44. DefaultBool check_mktemp;
  45. DefaultBool check_mkstemp;
  46. DefaultBool check_strcpy;
  47. DefaultBool check_rand;
  48. DefaultBool check_vfork;
  49. DefaultBool check_FloatLoopCounter;
  50. DefaultBool check_UncheckedReturn;
  51. };
  52. class WalkAST : public StmtVisitor<WalkAST> {
  53. BugReporter &BR;
  54. AnalysisDeclContext* AC;
  55. enum { num_setids = 6 };
  56. IdentifierInfo *II_setid[num_setids];
  57. const bool CheckRand;
  58. const ChecksFilter &filter;
  59. public:
  60. WalkAST(BugReporter &br, AnalysisDeclContext* ac,
  61. const ChecksFilter &f)
  62. : BR(br), AC(ac), II_setid(),
  63. CheckRand(isArc4RandomAvailable(BR.getContext())),
  64. filter(f) {}
  65. // Statement visitor methods.
  66. void VisitCallExpr(CallExpr *CE);
  67. void VisitForStmt(ForStmt *S);
  68. void VisitCompoundStmt (CompoundStmt *S);
  69. void VisitStmt(Stmt *S) { VisitChildren(S); }
  70. void VisitChildren(Stmt *S);
  71. // Helpers.
  72. bool checkCall_strCommon(const CallExpr *CE, const FunctionDecl *FD);
  73. typedef void (WalkAST::*FnCheck)(const CallExpr *,
  74. const FunctionDecl *);
  75. // Checker-specific methods.
  76. void checkLoopConditionForFloat(const ForStmt *FS);
  77. void checkCall_gets(const CallExpr *CE, const FunctionDecl *FD);
  78. void checkCall_getpw(const CallExpr *CE, const FunctionDecl *FD);
  79. void checkCall_mktemp(const CallExpr *CE, const FunctionDecl *FD);
  80. void checkCall_mkstemp(const CallExpr *CE, const FunctionDecl *FD);
  81. void checkCall_strcpy(const CallExpr *CE, const FunctionDecl *FD);
  82. void checkCall_strcat(const CallExpr *CE, const FunctionDecl *FD);
  83. void checkCall_rand(const CallExpr *CE, const FunctionDecl *FD);
  84. void checkCall_random(const CallExpr *CE, const FunctionDecl *FD);
  85. void checkCall_vfork(const CallExpr *CE, const FunctionDecl *FD);
  86. void checkUncheckedReturnValue(CallExpr *CE);
  87. };
  88. } // end anonymous namespace
  89. //===----------------------------------------------------------------------===//
  90. // AST walking.
  91. //===----------------------------------------------------------------------===//
  92. void WalkAST::VisitChildren(Stmt *S) {
  93. for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
  94. if (Stmt *child = *I)
  95. Visit(child);
  96. }
  97. void WalkAST::VisitCallExpr(CallExpr *CE) {
  98. // Get the callee.
  99. const FunctionDecl *FD = CE->getDirectCallee();
  100. if (!FD)
  101. return;
  102. // Get the name of the callee. If it's a builtin, strip off the prefix.
  103. IdentifierInfo *II = FD->getIdentifier();
  104. if (!II) // if no identifier, not a simple C function
  105. return;
  106. StringRef Name = II->getName();
  107. if (Name.startswith("__builtin_"))
  108. Name = Name.substr(10);
  109. // Set the evaluation function by switching on the callee name.
  110. FnCheck evalFunction = llvm::StringSwitch<FnCheck>(Name)
  111. .Case("gets", &WalkAST::checkCall_gets)
  112. .Case("getpw", &WalkAST::checkCall_getpw)
  113. .Case("mktemp", &WalkAST::checkCall_mktemp)
  114. .Case("mkstemp", &WalkAST::checkCall_mkstemp)
  115. .Case("mkdtemp", &WalkAST::checkCall_mkstemp)
  116. .Case("mkstemps", &WalkAST::checkCall_mkstemp)
  117. .Cases("strcpy", "__strcpy_chk", &WalkAST::checkCall_strcpy)
  118. .Cases("strcat", "__strcat_chk", &WalkAST::checkCall_strcat)
  119. .Case("drand48", &WalkAST::checkCall_rand)
  120. .Case("erand48", &WalkAST::checkCall_rand)
  121. .Case("jrand48", &WalkAST::checkCall_rand)
  122. .Case("lrand48", &WalkAST::checkCall_rand)
  123. .Case("mrand48", &WalkAST::checkCall_rand)
  124. .Case("nrand48", &WalkAST::checkCall_rand)
  125. .Case("lcong48", &WalkAST::checkCall_rand)
  126. .Case("rand", &WalkAST::checkCall_rand)
  127. .Case("rand_r", &WalkAST::checkCall_rand)
  128. .Case("random", &WalkAST::checkCall_random)
  129. .Case("vfork", &WalkAST::checkCall_vfork)
  130. .Default(NULL);
  131. // If the callee isn't defined, it is not of security concern.
  132. // Check and evaluate the call.
  133. if (evalFunction)
  134. (this->*evalFunction)(CE, FD);
  135. // Recurse and check children.
  136. VisitChildren(CE);
  137. }
  138. void WalkAST::VisitCompoundStmt(CompoundStmt *S) {
  139. for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
  140. if (Stmt *child = *I) {
  141. if (CallExpr *CE = dyn_cast<CallExpr>(child))
  142. checkUncheckedReturnValue(CE);
  143. Visit(child);
  144. }
  145. }
  146. void WalkAST::VisitForStmt(ForStmt *FS) {
  147. checkLoopConditionForFloat(FS);
  148. // Recurse and check children.
  149. VisitChildren(FS);
  150. }
  151. //===----------------------------------------------------------------------===//
  152. // Check: floating poing variable used as loop counter.
  153. // Originally: <rdar://problem/6336718>
  154. // Implements: CERT security coding advisory FLP-30.
  155. //===----------------------------------------------------------------------===//
  156. static const DeclRefExpr*
  157. getIncrementedVar(const Expr *expr, const VarDecl *x, const VarDecl *y) {
  158. expr = expr->IgnoreParenCasts();
  159. if (const BinaryOperator *B = dyn_cast<BinaryOperator>(expr)) {
  160. if (!(B->isAssignmentOp() || B->isCompoundAssignmentOp() ||
  161. B->getOpcode() == BO_Comma))
  162. return NULL;
  163. if (const DeclRefExpr *lhs = getIncrementedVar(B->getLHS(), x, y))
  164. return lhs;
  165. if (const DeclRefExpr *rhs = getIncrementedVar(B->getRHS(), x, y))
  166. return rhs;
  167. return NULL;
  168. }
  169. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(expr)) {
  170. const NamedDecl *ND = DR->getDecl();
  171. return ND == x || ND == y ? DR : NULL;
  172. }
  173. if (const UnaryOperator *U = dyn_cast<UnaryOperator>(expr))
  174. return U->isIncrementDecrementOp()
  175. ? getIncrementedVar(U->getSubExpr(), x, y) : NULL;
  176. return NULL;
  177. }
  178. /// CheckLoopConditionForFloat - This check looks for 'for' statements that
  179. /// use a floating point variable as a loop counter.
  180. /// CERT: FLP30-C, FLP30-CPP.
  181. ///
  182. void WalkAST::checkLoopConditionForFloat(const ForStmt *FS) {
  183. if (!filter.check_FloatLoopCounter)
  184. return;
  185. // Does the loop have a condition?
  186. const Expr *condition = FS->getCond();
  187. if (!condition)
  188. return;
  189. // Does the loop have an increment?
  190. const Expr *increment = FS->getInc();
  191. if (!increment)
  192. return;
  193. // Strip away '()' and casts.
  194. condition = condition->IgnoreParenCasts();
  195. increment = increment->IgnoreParenCasts();
  196. // Is the loop condition a comparison?
  197. const BinaryOperator *B = dyn_cast<BinaryOperator>(condition);
  198. if (!B)
  199. return;
  200. // Is this a comparison?
  201. if (!(B->isRelationalOp() || B->isEqualityOp()))
  202. return;
  203. // Are we comparing variables?
  204. const DeclRefExpr *drLHS =
  205. dyn_cast<DeclRefExpr>(B->getLHS()->IgnoreParenLValueCasts());
  206. const DeclRefExpr *drRHS =
  207. dyn_cast<DeclRefExpr>(B->getRHS()->IgnoreParenLValueCasts());
  208. // Does at least one of the variables have a floating point type?
  209. drLHS = drLHS && drLHS->getType()->isRealFloatingType() ? drLHS : NULL;
  210. drRHS = drRHS && drRHS->getType()->isRealFloatingType() ? drRHS : NULL;
  211. if (!drLHS && !drRHS)
  212. return;
  213. const VarDecl *vdLHS = drLHS ? dyn_cast<VarDecl>(drLHS->getDecl()) : NULL;
  214. const VarDecl *vdRHS = drRHS ? dyn_cast<VarDecl>(drRHS->getDecl()) : NULL;
  215. if (!vdLHS && !vdRHS)
  216. return;
  217. // Does either variable appear in increment?
  218. const DeclRefExpr *drInc = getIncrementedVar(increment, vdLHS, vdRHS);
  219. if (!drInc)
  220. return;
  221. // Emit the error. First figure out which DeclRefExpr in the condition
  222. // referenced the compared variable.
  223. const DeclRefExpr *drCond = vdLHS == drInc->getDecl() ? drLHS : drRHS;
  224. SmallVector<SourceRange, 2> ranges;
  225. SmallString<256> sbuf;
  226. llvm::raw_svector_ostream os(sbuf);
  227. os << "Variable '" << drCond->getDecl()->getName()
  228. << "' with floating point type '" << drCond->getType().getAsString()
  229. << "' should not be used as a loop counter";
  230. ranges.push_back(drCond->getSourceRange());
  231. ranges.push_back(drInc->getSourceRange());
  232. const char *bugType = "Floating point variable used as loop counter";
  233. PathDiagnosticLocation FSLoc =
  234. PathDiagnosticLocation::createBegin(FS, BR.getSourceManager(), AC);
  235. BR.EmitBasicReport(AC->getDecl(),
  236. bugType, "Security", os.str(),
  237. FSLoc, ranges.data(), ranges.size());
  238. }
  239. //===----------------------------------------------------------------------===//
  240. // Check: Any use of 'gets' is insecure.
  241. // Originally: <rdar://problem/6335715>
  242. // Implements (part of): 300-BSI (buildsecurityin.us-cert.gov)
  243. // CWE-242: Use of Inherently Dangerous Function
  244. //===----------------------------------------------------------------------===//
  245. void WalkAST::checkCall_gets(const CallExpr *CE, const FunctionDecl *FD) {
  246. if (!filter.check_gets)
  247. return;
  248. const FunctionProtoType *FPT
  249. = dyn_cast<FunctionProtoType>(FD->getType().IgnoreParens());
  250. if (!FPT)
  251. return;
  252. // Verify that the function takes a single argument.
  253. if (FPT->getNumArgs() != 1)
  254. return;
  255. // Is the argument a 'char*'?
  256. const PointerType *PT = dyn_cast<PointerType>(FPT->getArgType(0));
  257. if (!PT)
  258. return;
  259. if (PT->getPointeeType().getUnqualifiedType() != BR.getContext().CharTy)
  260. return;
  261. // Issue a warning.
  262. SourceRange R = CE->getCallee()->getSourceRange();
  263. PathDiagnosticLocation CELoc =
  264. PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
  265. BR.EmitBasicReport(AC->getDecl(),
  266. "Potential buffer overflow in call to 'gets'",
  267. "Security",
  268. "Call to function 'gets' is extremely insecure as it can "
  269. "always result in a buffer overflow",
  270. CELoc, &R, 1);
  271. }
  272. //===----------------------------------------------------------------------===//
  273. // Check: Any use of 'getpwd' is insecure.
  274. // CWE-477: Use of Obsolete Functions
  275. //===----------------------------------------------------------------------===//
  276. void WalkAST::checkCall_getpw(const CallExpr *CE, const FunctionDecl *FD) {
  277. if (!filter.check_getpw)
  278. return;
  279. const FunctionProtoType *FPT
  280. = dyn_cast<FunctionProtoType>(FD->getType().IgnoreParens());
  281. if (!FPT)
  282. return;
  283. // Verify that the function takes two arguments.
  284. if (FPT->getNumArgs() != 2)
  285. return;
  286. // Verify the first argument type is integer.
  287. if (!FPT->getArgType(0)->isIntegerType())
  288. return;
  289. // Verify the second argument type is char*.
  290. const PointerType *PT = dyn_cast<PointerType>(FPT->getArgType(1));
  291. if (!PT)
  292. return;
  293. if (PT->getPointeeType().getUnqualifiedType() != BR.getContext().CharTy)
  294. return;
  295. // Issue a warning.
  296. SourceRange R = CE->getCallee()->getSourceRange();
  297. PathDiagnosticLocation CELoc =
  298. PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
  299. BR.EmitBasicReport(AC->getDecl(),
  300. "Potential buffer overflow in call to 'getpw'",
  301. "Security",
  302. "The getpw() function is dangerous as it may overflow the "
  303. "provided buffer. It is obsoleted by getpwuid().",
  304. CELoc, &R, 1);
  305. }
  306. //===----------------------------------------------------------------------===//
  307. // Check: Any use of 'mktemp' is insecure. It is obsoleted by mkstemp().
  308. // CWE-377: Insecure Temporary File
  309. //===----------------------------------------------------------------------===//
  310. void WalkAST::checkCall_mktemp(const CallExpr *CE, const FunctionDecl *FD) {
  311. if (!filter.check_mktemp) {
  312. // Fall back to the security check of looking for enough 'X's in the
  313. // format string, since that is a less severe warning.
  314. checkCall_mkstemp(CE, FD);
  315. return;
  316. }
  317. const FunctionProtoType *FPT
  318. = dyn_cast<FunctionProtoType>(FD->getType().IgnoreParens());
  319. if(!FPT)
  320. return;
  321. // Verify that the function takes a single argument.
  322. if (FPT->getNumArgs() != 1)
  323. return;
  324. // Verify that the argument is Pointer Type.
  325. const PointerType *PT = dyn_cast<PointerType>(FPT->getArgType(0));
  326. if (!PT)
  327. return;
  328. // Verify that the argument is a 'char*'.
  329. if (PT->getPointeeType().getUnqualifiedType() != BR.getContext().CharTy)
  330. return;
  331. // Issue a waring.
  332. SourceRange R = CE->getCallee()->getSourceRange();
  333. PathDiagnosticLocation CELoc =
  334. PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
  335. BR.EmitBasicReport(AC->getDecl(),
  336. "Potential insecure temporary file in call 'mktemp'",
  337. "Security",
  338. "Call to function 'mktemp' is insecure as it always "
  339. "creates or uses insecure temporary file. Use 'mkstemp' "
  340. "instead",
  341. CELoc, &R, 1);
  342. }
  343. //===----------------------------------------------------------------------===//
  344. // Check: Use of 'mkstemp', 'mktemp', 'mkdtemp' should contain at least 6 X's.
  345. //===----------------------------------------------------------------------===//
  346. void WalkAST::checkCall_mkstemp(const CallExpr *CE, const FunctionDecl *FD) {
  347. if (!filter.check_mkstemp)
  348. return;
  349. StringRef Name = FD->getIdentifier()->getName();
  350. std::pair<signed, signed> ArgSuffix =
  351. llvm::StringSwitch<std::pair<signed, signed> >(Name)
  352. .Case("mktemp", std::make_pair(0,-1))
  353. .Case("mkstemp", std::make_pair(0,-1))
  354. .Case("mkdtemp", std::make_pair(0,-1))
  355. .Case("mkstemps", std::make_pair(0,1))
  356. .Default(std::make_pair(-1, -1));
  357. assert(ArgSuffix.first >= 0 && "Unsupported function");
  358. // Check if the number of arguments is consistent with out expectations.
  359. unsigned numArgs = CE->getNumArgs();
  360. if ((signed) numArgs <= ArgSuffix.first)
  361. return;
  362. const StringLiteral *strArg =
  363. dyn_cast<StringLiteral>(CE->getArg((unsigned)ArgSuffix.first)
  364. ->IgnoreParenImpCasts());
  365. // Currently we only handle string literals. It is possible to do better,
  366. // either by looking at references to const variables, or by doing real
  367. // flow analysis.
  368. if (!strArg || strArg->getCharByteWidth() != 1)
  369. return;
  370. // Count the number of X's, taking into account a possible cutoff suffix.
  371. StringRef str = strArg->getString();
  372. unsigned numX = 0;
  373. unsigned n = str.size();
  374. // Take into account the suffix.
  375. unsigned suffix = 0;
  376. if (ArgSuffix.second >= 0) {
  377. const Expr *suffixEx = CE->getArg((unsigned)ArgSuffix.second);
  378. llvm::APSInt Result;
  379. if (!suffixEx->EvaluateAsInt(Result, BR.getContext()))
  380. return;
  381. // FIXME: Issue a warning.
  382. if (Result.isNegative())
  383. return;
  384. suffix = (unsigned) Result.getZExtValue();
  385. n = (n > suffix) ? n - suffix : 0;
  386. }
  387. for (unsigned i = 0; i < n; ++i)
  388. if (str[i] == 'X') ++numX;
  389. if (numX >= 6)
  390. return;
  391. // Issue a warning.
  392. SourceRange R = strArg->getSourceRange();
  393. PathDiagnosticLocation CELoc =
  394. PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
  395. SmallString<512> buf;
  396. llvm::raw_svector_ostream out(buf);
  397. out << "Call to '" << Name << "' should have at least 6 'X's in the"
  398. " format string to be secure (" << numX << " 'X'";
  399. if (numX != 1)
  400. out << 's';
  401. out << " seen";
  402. if (suffix) {
  403. out << ", " << suffix << " character";
  404. if (suffix > 1)
  405. out << 's';
  406. out << " used as a suffix";
  407. }
  408. out << ')';
  409. BR.EmitBasicReport(AC->getDecl(),
  410. "Insecure temporary file creation", "Security",
  411. out.str(), CELoc, &R, 1);
  412. }
  413. //===----------------------------------------------------------------------===//
  414. // Check: Any use of 'strcpy' is insecure.
  415. //
  416. // CWE-119: Improper Restriction of Operations within
  417. // the Bounds of a Memory Buffer
  418. //===----------------------------------------------------------------------===//
  419. void WalkAST::checkCall_strcpy(const CallExpr *CE, const FunctionDecl *FD) {
  420. if (!filter.check_strcpy)
  421. return;
  422. if (!checkCall_strCommon(CE, FD))
  423. return;
  424. // Issue a warning.
  425. SourceRange R = CE->getCallee()->getSourceRange();
  426. PathDiagnosticLocation CELoc =
  427. PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
  428. BR.EmitBasicReport(AC->getDecl(),
  429. "Potential insecure memory buffer bounds restriction in "
  430. "call 'strcpy'",
  431. "Security",
  432. "Call to function 'strcpy' is insecure as it does not "
  433. "provide bounding of the memory buffer. Replace "
  434. "unbounded copy functions with analogous functions that "
  435. "support length arguments such as 'strlcpy'. CWE-119.",
  436. CELoc, &R, 1);
  437. }
  438. //===----------------------------------------------------------------------===//
  439. // Check: Any use of 'strcat' is insecure.
  440. //
  441. // CWE-119: Improper Restriction of Operations within
  442. // the Bounds of a Memory Buffer
  443. //===----------------------------------------------------------------------===//
  444. void WalkAST::checkCall_strcat(const CallExpr *CE, const FunctionDecl *FD) {
  445. if (!filter.check_strcpy)
  446. return;
  447. if (!checkCall_strCommon(CE, FD))
  448. return;
  449. // Issue a warning.
  450. SourceRange R = CE->getCallee()->getSourceRange();
  451. PathDiagnosticLocation CELoc =
  452. PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
  453. BR.EmitBasicReport(AC->getDecl(),
  454. "Potential insecure memory buffer bounds restriction in "
  455. "call 'strcat'",
  456. "Security",
  457. "Call to function 'strcat' is insecure as it does not "
  458. "provide bounding of the memory buffer. Replace "
  459. "unbounded copy functions with analogous functions that "
  460. "support length arguments such as 'strlcat'. CWE-119.",
  461. CELoc, &R, 1);
  462. }
  463. //===----------------------------------------------------------------------===//
  464. // Common check for str* functions with no bounds parameters.
  465. //===----------------------------------------------------------------------===//
  466. bool WalkAST::checkCall_strCommon(const CallExpr *CE, const FunctionDecl *FD) {
  467. const FunctionProtoType *FPT
  468. = dyn_cast<FunctionProtoType>(FD->getType().IgnoreParens());
  469. if (!FPT)
  470. return false;
  471. // Verify the function takes two arguments, three in the _chk version.
  472. int numArgs = FPT->getNumArgs();
  473. if (numArgs != 2 && numArgs != 3)
  474. return false;
  475. // Verify the type for both arguments.
  476. for (int i = 0; i < 2; i++) {
  477. // Verify that the arguments are pointers.
  478. const PointerType *PT = dyn_cast<PointerType>(FPT->getArgType(i));
  479. if (!PT)
  480. return false;
  481. // Verify that the argument is a 'char*'.
  482. if (PT->getPointeeType().getUnqualifiedType() != BR.getContext().CharTy)
  483. return false;
  484. }
  485. return true;
  486. }
  487. //===----------------------------------------------------------------------===//
  488. // Check: Linear congruent random number generators should not be used
  489. // Originally: <rdar://problem/63371000>
  490. // CWE-338: Use of cryptographically weak prng
  491. //===----------------------------------------------------------------------===//
  492. void WalkAST::checkCall_rand(const CallExpr *CE, const FunctionDecl *FD) {
  493. if (!filter.check_rand || !CheckRand)
  494. return;
  495. const FunctionProtoType *FTP
  496. = dyn_cast<FunctionProtoType>(FD->getType().IgnoreParens());
  497. if (!FTP)
  498. return;
  499. if (FTP->getNumArgs() == 1) {
  500. // Is the argument an 'unsigned short *'?
  501. // (Actually any integer type is allowed.)
  502. const PointerType *PT = dyn_cast<PointerType>(FTP->getArgType(0));
  503. if (!PT)
  504. return;
  505. if (! PT->getPointeeType()->isIntegerType())
  506. return;
  507. }
  508. else if (FTP->getNumArgs() != 0)
  509. return;
  510. // Issue a warning.
  511. SmallString<256> buf1;
  512. llvm::raw_svector_ostream os1(buf1);
  513. os1 << '\'' << *FD << "' is a poor random number generator";
  514. SmallString<256> buf2;
  515. llvm::raw_svector_ostream os2(buf2);
  516. os2 << "Function '" << *FD
  517. << "' is obsolete because it implements a poor random number generator."
  518. << " Use 'arc4random' instead";
  519. SourceRange R = CE->getCallee()->getSourceRange();
  520. PathDiagnosticLocation CELoc =
  521. PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
  522. BR.EmitBasicReport(AC->getDecl(), os1.str(), "Security", os2.str(),
  523. CELoc, &R, 1);
  524. }
  525. //===----------------------------------------------------------------------===//
  526. // Check: 'random' should not be used
  527. // Originally: <rdar://problem/63371000>
  528. //===----------------------------------------------------------------------===//
  529. void WalkAST::checkCall_random(const CallExpr *CE, const FunctionDecl *FD) {
  530. if (!CheckRand || !filter.check_rand)
  531. return;
  532. const FunctionProtoType *FTP
  533. = dyn_cast<FunctionProtoType>(FD->getType().IgnoreParens());
  534. if (!FTP)
  535. return;
  536. // Verify that the function takes no argument.
  537. if (FTP->getNumArgs() != 0)
  538. return;
  539. // Issue a warning.
  540. SourceRange R = CE->getCallee()->getSourceRange();
  541. PathDiagnosticLocation CELoc =
  542. PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
  543. BR.EmitBasicReport(AC->getDecl(),
  544. "'random' is not a secure random number generator",
  545. "Security",
  546. "The 'random' function produces a sequence of values that "
  547. "an adversary may be able to predict. Use 'arc4random' "
  548. "instead", CELoc, &R, 1);
  549. }
  550. //===----------------------------------------------------------------------===//
  551. // Check: 'vfork' should not be used.
  552. // POS33-C: Do not use vfork().
  553. //===----------------------------------------------------------------------===//
  554. void WalkAST::checkCall_vfork(const CallExpr *CE, const FunctionDecl *FD) {
  555. if (!filter.check_vfork)
  556. return;
  557. // All calls to vfork() are insecure, issue a warning.
  558. SourceRange R = CE->getCallee()->getSourceRange();
  559. PathDiagnosticLocation CELoc =
  560. PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
  561. BR.EmitBasicReport(AC->getDecl(),
  562. "Potential insecure implementation-specific behavior in "
  563. "call 'vfork'",
  564. "Security",
  565. "Call to function 'vfork' is insecure as it can lead to "
  566. "denial of service situations in the parent process. "
  567. "Replace calls to vfork with calls to the safer "
  568. "'posix_spawn' function",
  569. CELoc, &R, 1);
  570. }
  571. //===----------------------------------------------------------------------===//
  572. // Check: Should check whether privileges are dropped successfully.
  573. // Originally: <rdar://problem/6337132>
  574. //===----------------------------------------------------------------------===//
  575. void WalkAST::checkUncheckedReturnValue(CallExpr *CE) {
  576. if (!filter.check_UncheckedReturn)
  577. return;
  578. const FunctionDecl *FD = CE->getDirectCallee();
  579. if (!FD)
  580. return;
  581. if (II_setid[0] == NULL) {
  582. static const char * const identifiers[num_setids] = {
  583. "setuid", "setgid", "seteuid", "setegid",
  584. "setreuid", "setregid"
  585. };
  586. for (size_t i = 0; i < num_setids; i++)
  587. II_setid[i] = &BR.getContext().Idents.get(identifiers[i]);
  588. }
  589. const IdentifierInfo *id = FD->getIdentifier();
  590. size_t identifierid;
  591. for (identifierid = 0; identifierid < num_setids; identifierid++)
  592. if (id == II_setid[identifierid])
  593. break;
  594. if (identifierid >= num_setids)
  595. return;
  596. const FunctionProtoType *FTP
  597. = dyn_cast<FunctionProtoType>(FD->getType().IgnoreParens());
  598. if (!FTP)
  599. return;
  600. // Verify that the function takes one or two arguments (depending on
  601. // the function).
  602. if (FTP->getNumArgs() != (identifierid < 4 ? 1 : 2))
  603. return;
  604. // The arguments must be integers.
  605. for (unsigned i = 0; i < FTP->getNumArgs(); i++)
  606. if (! FTP->getArgType(i)->isIntegerType())
  607. return;
  608. // Issue a warning.
  609. SmallString<256> buf1;
  610. llvm::raw_svector_ostream os1(buf1);
  611. os1 << "Return value is not checked in call to '" << *FD << '\'';
  612. SmallString<256> buf2;
  613. llvm::raw_svector_ostream os2(buf2);
  614. os2 << "The return value from the call to '" << *FD
  615. << "' is not checked. If an error occurs in '" << *FD
  616. << "', the following code may execute with unexpected privileges";
  617. SourceRange R = CE->getCallee()->getSourceRange();
  618. PathDiagnosticLocation CELoc =
  619. PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
  620. BR.EmitBasicReport(AC->getDecl(), os1.str(), "Security", os2.str(),
  621. CELoc, &R, 1);
  622. }
  623. //===----------------------------------------------------------------------===//
  624. // SecuritySyntaxChecker
  625. //===----------------------------------------------------------------------===//
  626. namespace {
  627. class SecuritySyntaxChecker : public Checker<check::ASTCodeBody> {
  628. public:
  629. ChecksFilter filter;
  630. void checkASTCodeBody(const Decl *D, AnalysisManager& mgr,
  631. BugReporter &BR) const {
  632. WalkAST walker(BR, mgr.getAnalysisDeclContext(D), filter);
  633. walker.Visit(D->getBody());
  634. }
  635. };
  636. }
  637. #define REGISTER_CHECKER(name) \
  638. void ento::register##name(CheckerManager &mgr) {\
  639. mgr.registerChecker<SecuritySyntaxChecker>()->filter.check_##name = true;\
  640. }
  641. REGISTER_CHECKER(gets)
  642. REGISTER_CHECKER(getpw)
  643. REGISTER_CHECKER(mkstemp)
  644. REGISTER_CHECKER(mktemp)
  645. REGISTER_CHECKER(strcpy)
  646. REGISTER_CHECKER(rand)
  647. REGISTER_CHECKER(vfork)
  648. REGISTER_CHECKER(FloatLoopCounter)
  649. REGISTER_CHECKER(UncheckedReturn)