CheckSecuritySyntaxOnly.cpp 32 KB

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