CheckSecuritySyntaxOnly.cpp 26 KB

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