CheckSecuritySyntaxOnly.cpp 27 KB

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