CheckSecuritySyntaxOnly.cpp 27 KB

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