CheckSecuritySyntaxOnly.cpp 27 KB

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