CheckSecuritySyntaxOnly.cpp 26 KB

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