CheckSecuritySyntaxOnly.cpp 26 KB

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