CheckSecuritySyntaxOnly.cpp 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104
  1. //==- CheckSecuritySyntaxOnly.cpp - Basic security checks --------*- C++ -*-==//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file defines a set of flow-insensitive security checks.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
  13. #include "clang/AST/StmtVisitor.h"
  14. #include "clang/Analysis/AnalysisDeclContext.h"
  15. #include "clang/Basic/TargetInfo.h"
  16. #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
  17. #include "clang/StaticAnalyzer/Core/Checker.h"
  18. #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
  19. #include "llvm/ADT/SmallString.h"
  20. #include "llvm/ADT/StringSwitch.h"
  21. #include "llvm/Support/raw_ostream.h"
  22. using namespace clang;
  23. using namespace ento;
  24. static bool isArc4RandomAvailable(const ASTContext &Ctx) {
  25. const llvm::Triple &T = Ctx.getTargetInfo().getTriple();
  26. return T.getVendor() == llvm::Triple::Apple ||
  27. T.getOS() == llvm::Triple::CloudABI ||
  28. T.isOSFreeBSD() ||
  29. T.isOSNetBSD() ||
  30. T.isOSOpenBSD() ||
  31. T.isOSDragonFly();
  32. }
  33. namespace {
  34. struct ChecksFilter {
  35. DefaultBool check_bcmp;
  36. DefaultBool check_bcopy;
  37. DefaultBool check_bzero;
  38. DefaultBool check_gets;
  39. DefaultBool check_getpw;
  40. DefaultBool check_mktemp;
  41. DefaultBool check_mkstemp;
  42. DefaultBool check_strcpy;
  43. DefaultBool check_DeprecatedOrUnsafeBufferHandling;
  44. DefaultBool check_rand;
  45. DefaultBool check_vfork;
  46. DefaultBool check_FloatLoopCounter;
  47. DefaultBool check_UncheckedReturn;
  48. DefaultBool check_decodeValueOfObjCType;
  49. CheckerNameRef checkName_bcmp;
  50. CheckerNameRef checkName_bcopy;
  51. CheckerNameRef checkName_bzero;
  52. CheckerNameRef checkName_gets;
  53. CheckerNameRef checkName_getpw;
  54. CheckerNameRef checkName_mktemp;
  55. CheckerNameRef checkName_mkstemp;
  56. CheckerNameRef checkName_strcpy;
  57. CheckerNameRef checkName_DeprecatedOrUnsafeBufferHandling;
  58. CheckerNameRef checkName_rand;
  59. CheckerNameRef checkName_vfork;
  60. CheckerNameRef checkName_FloatLoopCounter;
  61. CheckerNameRef checkName_UncheckedReturn;
  62. CheckerNameRef checkName_decodeValueOfObjCType;
  63. };
  64. class WalkAST : public StmtVisitor<WalkAST> {
  65. BugReporter &BR;
  66. AnalysisDeclContext* AC;
  67. enum { num_setids = 6 };
  68. IdentifierInfo *II_setid[num_setids];
  69. const bool CheckRand;
  70. const ChecksFilter &filter;
  71. public:
  72. WalkAST(BugReporter &br, AnalysisDeclContext* ac,
  73. const ChecksFilter &f)
  74. : BR(br), AC(ac), II_setid(),
  75. CheckRand(isArc4RandomAvailable(BR.getContext())),
  76. filter(f) {}
  77. // Statement visitor methods.
  78. void VisitCallExpr(CallExpr *CE);
  79. void VisitObjCMessageExpr(ObjCMessageExpr *CE);
  80. void VisitForStmt(ForStmt *S);
  81. void VisitCompoundStmt (CompoundStmt *S);
  82. void VisitStmt(Stmt *S) { VisitChildren(S); }
  83. void VisitChildren(Stmt *S);
  84. // Helpers.
  85. bool checkCall_strCommon(const CallExpr *CE, const FunctionDecl *FD);
  86. typedef void (WalkAST::*FnCheck)(const CallExpr *, const FunctionDecl *);
  87. typedef void (WalkAST::*MsgCheck)(const ObjCMessageExpr *);
  88. // Checker-specific methods.
  89. void checkLoopConditionForFloat(const ForStmt *FS);
  90. void checkCall_bcmp(const CallExpr *CE, const FunctionDecl *FD);
  91. void checkCall_bcopy(const CallExpr *CE, const FunctionDecl *FD);
  92. void checkCall_bzero(const CallExpr *CE, const FunctionDecl *FD);
  93. void checkCall_gets(const CallExpr *CE, const FunctionDecl *FD);
  94. void checkCall_getpw(const CallExpr *CE, const FunctionDecl *FD);
  95. void checkCall_mktemp(const CallExpr *CE, const FunctionDecl *FD);
  96. void checkCall_mkstemp(const CallExpr *CE, const FunctionDecl *FD);
  97. void checkCall_strcpy(const CallExpr *CE, const FunctionDecl *FD);
  98. void checkCall_strcat(const CallExpr *CE, const FunctionDecl *FD);
  99. void checkDeprecatedOrUnsafeBufferHandling(const CallExpr *CE,
  100. const FunctionDecl *FD);
  101. void checkCall_rand(const CallExpr *CE, const FunctionDecl *FD);
  102. void checkCall_random(const CallExpr *CE, const FunctionDecl *FD);
  103. void checkCall_vfork(const CallExpr *CE, const FunctionDecl *FD);
  104. void checkMsg_decodeValueOfObjCType(const ObjCMessageExpr *ME);
  105. void checkUncheckedReturnValue(CallExpr *CE);
  106. };
  107. } // end anonymous namespace
  108. //===----------------------------------------------------------------------===//
  109. // AST walking.
  110. //===----------------------------------------------------------------------===//
  111. void WalkAST::VisitChildren(Stmt *S) {
  112. for (Stmt *Child : S->children())
  113. if (Child)
  114. Visit(Child);
  115. }
  116. void WalkAST::VisitCallExpr(CallExpr *CE) {
  117. // Get the callee.
  118. const FunctionDecl *FD = CE->getDirectCallee();
  119. if (!FD)
  120. return;
  121. // Get the name of the callee. If it's a builtin, strip off the prefix.
  122. IdentifierInfo *II = FD->getIdentifier();
  123. if (!II) // if no identifier, not a simple C function
  124. return;
  125. StringRef Name = II->getName();
  126. if (Name.startswith("__builtin_"))
  127. Name = Name.substr(10);
  128. // Set the evaluation function by switching on the callee name.
  129. FnCheck evalFunction = llvm::StringSwitch<FnCheck>(Name)
  130. .Case("bcmp", &WalkAST::checkCall_bcmp)
  131. .Case("bcopy", &WalkAST::checkCall_bcopy)
  132. .Case("bzero", &WalkAST::checkCall_bzero)
  133. .Case("gets", &WalkAST::checkCall_gets)
  134. .Case("getpw", &WalkAST::checkCall_getpw)
  135. .Case("mktemp", &WalkAST::checkCall_mktemp)
  136. .Case("mkstemp", &WalkAST::checkCall_mkstemp)
  137. .Case("mkdtemp", &WalkAST::checkCall_mkstemp)
  138. .Case("mkstemps", &WalkAST::checkCall_mkstemp)
  139. .Cases("strcpy", "__strcpy_chk", &WalkAST::checkCall_strcpy)
  140. .Cases("strcat", "__strcat_chk", &WalkAST::checkCall_strcat)
  141. .Cases("sprintf", "vsprintf", "scanf", "wscanf", "fscanf", "fwscanf",
  142. "vscanf", "vwscanf", "vfscanf", "vfwscanf",
  143. &WalkAST::checkDeprecatedOrUnsafeBufferHandling)
  144. .Cases("sscanf", "swscanf", "vsscanf", "vswscanf", "swprintf",
  145. "snprintf", "vswprintf", "vsnprintf", "memcpy", "memmove",
  146. &WalkAST::checkDeprecatedOrUnsafeBufferHandling)
  147. .Cases("strncpy", "strncat", "memset",
  148. &WalkAST::checkDeprecatedOrUnsafeBufferHandling)
  149. .Case("drand48", &WalkAST::checkCall_rand)
  150. .Case("erand48", &WalkAST::checkCall_rand)
  151. .Case("jrand48", &WalkAST::checkCall_rand)
  152. .Case("lrand48", &WalkAST::checkCall_rand)
  153. .Case("mrand48", &WalkAST::checkCall_rand)
  154. .Case("nrand48", &WalkAST::checkCall_rand)
  155. .Case("lcong48", &WalkAST::checkCall_rand)
  156. .Case("rand", &WalkAST::checkCall_rand)
  157. .Case("rand_r", &WalkAST::checkCall_rand)
  158. .Case("random", &WalkAST::checkCall_random)
  159. .Case("vfork", &WalkAST::checkCall_vfork)
  160. .Default(nullptr);
  161. // If the callee isn't defined, it is not of security concern.
  162. // Check and evaluate the call.
  163. if (evalFunction)
  164. (this->*evalFunction)(CE, FD);
  165. // Recurse and check children.
  166. VisitChildren(CE);
  167. }
  168. void WalkAST::VisitObjCMessageExpr(ObjCMessageExpr *ME) {
  169. MsgCheck evalFunction =
  170. llvm::StringSwitch<MsgCheck>(ME->getSelector().getAsString())
  171. .Case("decodeValueOfObjCType:at:",
  172. &WalkAST::checkMsg_decodeValueOfObjCType)
  173. .Default(nullptr);
  174. if (evalFunction)
  175. (this->*evalFunction)(ME);
  176. // Recurse and check children.
  177. VisitChildren(ME);
  178. }
  179. void WalkAST::VisitCompoundStmt(CompoundStmt *S) {
  180. for (Stmt *Child : S->children())
  181. if (Child) {
  182. if (CallExpr *CE = dyn_cast<CallExpr>(Child))
  183. checkUncheckedReturnValue(CE);
  184. Visit(Child);
  185. }
  186. }
  187. void WalkAST::VisitForStmt(ForStmt *FS) {
  188. checkLoopConditionForFloat(FS);
  189. // Recurse and check children.
  190. VisitChildren(FS);
  191. }
  192. //===----------------------------------------------------------------------===//
  193. // Check: floating point variable used as loop counter.
  194. // Originally: <rdar://problem/6336718>
  195. // Implements: CERT security coding advisory FLP-30.
  196. //===----------------------------------------------------------------------===//
  197. // Returns either 'x' or 'y', depending on which one of them is incremented
  198. // in 'expr', or nullptr if none of them is incremented.
  199. static const DeclRefExpr*
  200. getIncrementedVar(const Expr *expr, const VarDecl *x, const VarDecl *y) {
  201. expr = expr->IgnoreParenCasts();
  202. if (const BinaryOperator *B = dyn_cast<BinaryOperator>(expr)) {
  203. if (!(B->isAssignmentOp() || B->isCompoundAssignmentOp() ||
  204. B->getOpcode() == BO_Comma))
  205. return nullptr;
  206. if (const DeclRefExpr *lhs = getIncrementedVar(B->getLHS(), x, y))
  207. return lhs;
  208. if (const DeclRefExpr *rhs = getIncrementedVar(B->getRHS(), x, y))
  209. return rhs;
  210. return nullptr;
  211. }
  212. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(expr)) {
  213. const NamedDecl *ND = DR->getDecl();
  214. return ND == x || ND == y ? DR : nullptr;
  215. }
  216. if (const UnaryOperator *U = dyn_cast<UnaryOperator>(expr))
  217. return U->isIncrementDecrementOp()
  218. ? getIncrementedVar(U->getSubExpr(), x, y) : nullptr;
  219. return nullptr;
  220. }
  221. /// CheckLoopConditionForFloat - This check looks for 'for' statements that
  222. /// use a floating point variable as a loop counter.
  223. /// CERT: FLP30-C, FLP30-CPP.
  224. ///
  225. void WalkAST::checkLoopConditionForFloat(const ForStmt *FS) {
  226. if (!filter.check_FloatLoopCounter)
  227. return;
  228. // Does the loop have a condition?
  229. const Expr *condition = FS->getCond();
  230. if (!condition)
  231. return;
  232. // Does the loop have an increment?
  233. const Expr *increment = FS->getInc();
  234. if (!increment)
  235. return;
  236. // Strip away '()' and casts.
  237. condition = condition->IgnoreParenCasts();
  238. increment = increment->IgnoreParenCasts();
  239. // Is the loop condition a comparison?
  240. const BinaryOperator *B = dyn_cast<BinaryOperator>(condition);
  241. if (!B)
  242. return;
  243. // Is this a comparison?
  244. if (!(B->isRelationalOp() || B->isEqualityOp()))
  245. return;
  246. // Are we comparing variables?
  247. const DeclRefExpr *drLHS =
  248. dyn_cast<DeclRefExpr>(B->getLHS()->IgnoreParenLValueCasts());
  249. const DeclRefExpr *drRHS =
  250. dyn_cast<DeclRefExpr>(B->getRHS()->IgnoreParenLValueCasts());
  251. // Does at least one of the variables have a floating point type?
  252. drLHS = drLHS && drLHS->getType()->isRealFloatingType() ? drLHS : nullptr;
  253. drRHS = drRHS && drRHS->getType()->isRealFloatingType() ? drRHS : nullptr;
  254. if (!drLHS && !drRHS)
  255. return;
  256. const VarDecl *vdLHS = drLHS ? dyn_cast<VarDecl>(drLHS->getDecl()) : nullptr;
  257. const VarDecl *vdRHS = drRHS ? dyn_cast<VarDecl>(drRHS->getDecl()) : nullptr;
  258. if (!vdLHS && !vdRHS)
  259. return;
  260. // Does either variable appear in increment?
  261. const DeclRefExpr *drInc = getIncrementedVar(increment, vdLHS, vdRHS);
  262. if (!drInc)
  263. return;
  264. const VarDecl *vdInc = cast<VarDecl>(drInc->getDecl());
  265. assert(vdInc && (vdInc == vdLHS || vdInc == vdRHS));
  266. // Emit the error. First figure out which DeclRefExpr in the condition
  267. // referenced the compared variable.
  268. const DeclRefExpr *drCond = vdLHS == vdInc ? drLHS : drRHS;
  269. SmallVector<SourceRange, 2> ranges;
  270. SmallString<256> sbuf;
  271. llvm::raw_svector_ostream os(sbuf);
  272. os << "Variable '" << drCond->getDecl()->getName()
  273. << "' with floating point type '" << drCond->getType().getAsString()
  274. << "' should not be used as a loop counter";
  275. ranges.push_back(drCond->getSourceRange());
  276. ranges.push_back(drInc->getSourceRange());
  277. const char *bugType = "Floating point variable used as loop counter";
  278. PathDiagnosticLocation FSLoc =
  279. PathDiagnosticLocation::createBegin(FS, BR.getSourceManager(), AC);
  280. BR.EmitBasicReport(AC->getDecl(), filter.checkName_FloatLoopCounter,
  281. bugType, "Security", os.str(),
  282. FSLoc, ranges);
  283. }
  284. //===----------------------------------------------------------------------===//
  285. // Check: Any use of bcmp.
  286. // CWE-477: Use of Obsolete Functions
  287. // bcmp was deprecated in POSIX.1-2008
  288. //===----------------------------------------------------------------------===//
  289. void WalkAST::checkCall_bcmp(const CallExpr *CE, const FunctionDecl *FD) {
  290. if (!filter.check_bcmp)
  291. return;
  292. const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>();
  293. if (!FPT)
  294. return;
  295. // Verify that the function takes three arguments.
  296. if (FPT->getNumParams() != 3)
  297. return;
  298. for (int i = 0; i < 2; i++) {
  299. // Verify the first and second argument type is void*.
  300. const PointerType *PT = FPT->getParamType(i)->getAs<PointerType>();
  301. if (!PT)
  302. return;
  303. if (PT->getPointeeType().getUnqualifiedType() != BR.getContext().VoidTy)
  304. return;
  305. }
  306. // Verify the third argument type is integer.
  307. if (!FPT->getParamType(2)->isIntegralOrUnscopedEnumerationType())
  308. return;
  309. // Issue a warning.
  310. PathDiagnosticLocation CELoc =
  311. PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
  312. BR.EmitBasicReport(AC->getDecl(), filter.checkName_bcmp,
  313. "Use of deprecated function in call to 'bcmp()'",
  314. "Security",
  315. "The bcmp() function is obsoleted by memcmp().",
  316. CELoc, CE->getCallee()->getSourceRange());
  317. }
  318. //===----------------------------------------------------------------------===//
  319. // Check: Any use of bcopy.
  320. // CWE-477: Use of Obsolete Functions
  321. // bcopy was deprecated in POSIX.1-2008
  322. //===----------------------------------------------------------------------===//
  323. void WalkAST::checkCall_bcopy(const CallExpr *CE, const FunctionDecl *FD) {
  324. if (!filter.check_bcopy)
  325. return;
  326. const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>();
  327. if (!FPT)
  328. return;
  329. // Verify that the function takes three arguments.
  330. if (FPT->getNumParams() != 3)
  331. return;
  332. for (int i = 0; i < 2; i++) {
  333. // Verify the first and second argument type is void*.
  334. const PointerType *PT = FPT->getParamType(i)->getAs<PointerType>();
  335. if (!PT)
  336. return;
  337. if (PT->getPointeeType().getUnqualifiedType() != BR.getContext().VoidTy)
  338. return;
  339. }
  340. // Verify the third argument type is integer.
  341. if (!FPT->getParamType(2)->isIntegralOrUnscopedEnumerationType())
  342. return;
  343. // Issue a warning.
  344. PathDiagnosticLocation CELoc =
  345. PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
  346. BR.EmitBasicReport(AC->getDecl(), filter.checkName_bcopy,
  347. "Use of deprecated function in call to 'bcopy()'",
  348. "Security",
  349. "The bcopy() function is obsoleted by memcpy() "
  350. "or memmove().",
  351. CELoc, CE->getCallee()->getSourceRange());
  352. }
  353. //===----------------------------------------------------------------------===//
  354. // Check: Any use of bzero.
  355. // CWE-477: Use of Obsolete Functions
  356. // bzero was deprecated in POSIX.1-2008
  357. //===----------------------------------------------------------------------===//
  358. void WalkAST::checkCall_bzero(const CallExpr *CE, const FunctionDecl *FD) {
  359. if (!filter.check_bzero)
  360. return;
  361. const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>();
  362. if (!FPT)
  363. return;
  364. // Verify that the function takes two arguments.
  365. if (FPT->getNumParams() != 2)
  366. return;
  367. // Verify the first argument type is void*.
  368. const PointerType *PT = FPT->getParamType(0)->getAs<PointerType>();
  369. if (!PT)
  370. return;
  371. if (PT->getPointeeType().getUnqualifiedType() != BR.getContext().VoidTy)
  372. return;
  373. // Verify the second argument type is integer.
  374. if (!FPT->getParamType(1)->isIntegralOrUnscopedEnumerationType())
  375. return;
  376. // Issue a warning.
  377. PathDiagnosticLocation CELoc =
  378. PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
  379. BR.EmitBasicReport(AC->getDecl(), filter.checkName_bzero,
  380. "Use of deprecated function in call to 'bzero()'",
  381. "Security",
  382. "The bzero() function is obsoleted by memset().",
  383. CELoc, CE->getCallee()->getSourceRange());
  384. }
  385. //===----------------------------------------------------------------------===//
  386. // Check: Any use of 'gets' is insecure.
  387. // Originally: <rdar://problem/6335715>
  388. // Implements (part of): 300-BSI (buildsecurityin.us-cert.gov)
  389. // CWE-242: Use of Inherently Dangerous Function
  390. //===----------------------------------------------------------------------===//
  391. void WalkAST::checkCall_gets(const CallExpr *CE, const FunctionDecl *FD) {
  392. if (!filter.check_gets)
  393. return;
  394. const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>();
  395. if (!FPT)
  396. return;
  397. // Verify that the function takes a single argument.
  398. if (FPT->getNumParams() != 1)
  399. return;
  400. // Is the argument a 'char*'?
  401. const PointerType *PT = FPT->getParamType(0)->getAs<PointerType>();
  402. if (!PT)
  403. return;
  404. if (PT->getPointeeType().getUnqualifiedType() != BR.getContext().CharTy)
  405. return;
  406. // Issue a warning.
  407. PathDiagnosticLocation CELoc =
  408. PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
  409. BR.EmitBasicReport(AC->getDecl(), filter.checkName_gets,
  410. "Potential buffer overflow in call to 'gets'",
  411. "Security",
  412. "Call to function 'gets' is extremely insecure as it can "
  413. "always result in a buffer overflow",
  414. CELoc, CE->getCallee()->getSourceRange());
  415. }
  416. //===----------------------------------------------------------------------===//
  417. // Check: Any use of 'getpwd' is insecure.
  418. // CWE-477: Use of Obsolete Functions
  419. //===----------------------------------------------------------------------===//
  420. void WalkAST::checkCall_getpw(const CallExpr *CE, const FunctionDecl *FD) {
  421. if (!filter.check_getpw)
  422. return;
  423. const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>();
  424. if (!FPT)
  425. return;
  426. // Verify that the function takes two arguments.
  427. if (FPT->getNumParams() != 2)
  428. return;
  429. // Verify the first argument type is integer.
  430. if (!FPT->getParamType(0)->isIntegralOrUnscopedEnumerationType())
  431. return;
  432. // Verify the second argument type is char*.
  433. const PointerType *PT = FPT->getParamType(1)->getAs<PointerType>();
  434. if (!PT)
  435. return;
  436. if (PT->getPointeeType().getUnqualifiedType() != BR.getContext().CharTy)
  437. return;
  438. // Issue a warning.
  439. PathDiagnosticLocation CELoc =
  440. PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
  441. BR.EmitBasicReport(AC->getDecl(), filter.checkName_getpw,
  442. "Potential buffer overflow in call to 'getpw'",
  443. "Security",
  444. "The getpw() function is dangerous as it may overflow the "
  445. "provided buffer. It is obsoleted by getpwuid().",
  446. CELoc, CE->getCallee()->getSourceRange());
  447. }
  448. //===----------------------------------------------------------------------===//
  449. // Check: Any use of 'mktemp' is insecure. It is obsoleted by mkstemp().
  450. // CWE-377: Insecure Temporary File
  451. //===----------------------------------------------------------------------===//
  452. void WalkAST::checkCall_mktemp(const CallExpr *CE, const FunctionDecl *FD) {
  453. if (!filter.check_mktemp) {
  454. // Fall back to the security check of looking for enough 'X's in the
  455. // format string, since that is a less severe warning.
  456. checkCall_mkstemp(CE, FD);
  457. return;
  458. }
  459. const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>();
  460. if(!FPT)
  461. return;
  462. // Verify that the function takes a single argument.
  463. if (FPT->getNumParams() != 1)
  464. return;
  465. // Verify that the argument is Pointer Type.
  466. const PointerType *PT = FPT->getParamType(0)->getAs<PointerType>();
  467. if (!PT)
  468. return;
  469. // Verify that the argument is a 'char*'.
  470. if (PT->getPointeeType().getUnqualifiedType() != BR.getContext().CharTy)
  471. return;
  472. // Issue a warning.
  473. PathDiagnosticLocation CELoc =
  474. PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
  475. BR.EmitBasicReport(AC->getDecl(), filter.checkName_mktemp,
  476. "Potential insecure temporary file in call 'mktemp'",
  477. "Security",
  478. "Call to function 'mktemp' is insecure as it always "
  479. "creates or uses insecure temporary file. Use 'mkstemp' "
  480. "instead",
  481. CELoc, CE->getCallee()->getSourceRange());
  482. }
  483. //===----------------------------------------------------------------------===//
  484. // Check: Use of 'mkstemp', 'mktemp', 'mkdtemp' should contain at least 6 X's.
  485. //===----------------------------------------------------------------------===//
  486. void WalkAST::checkCall_mkstemp(const CallExpr *CE, const FunctionDecl *FD) {
  487. if (!filter.check_mkstemp)
  488. return;
  489. StringRef Name = FD->getIdentifier()->getName();
  490. std::pair<signed, signed> ArgSuffix =
  491. llvm::StringSwitch<std::pair<signed, signed> >(Name)
  492. .Case("mktemp", std::make_pair(0,-1))
  493. .Case("mkstemp", std::make_pair(0,-1))
  494. .Case("mkdtemp", std::make_pair(0,-1))
  495. .Case("mkstemps", std::make_pair(0,1))
  496. .Default(std::make_pair(-1, -1));
  497. assert(ArgSuffix.first >= 0 && "Unsupported function");
  498. // Check if the number of arguments is consistent with out expectations.
  499. unsigned numArgs = CE->getNumArgs();
  500. if ((signed) numArgs <= ArgSuffix.first)
  501. return;
  502. const StringLiteral *strArg =
  503. dyn_cast<StringLiteral>(CE->getArg((unsigned)ArgSuffix.first)
  504. ->IgnoreParenImpCasts());
  505. // Currently we only handle string literals. It is possible to do better,
  506. // either by looking at references to const variables, or by doing real
  507. // flow analysis.
  508. if (!strArg || strArg->getCharByteWidth() != 1)
  509. return;
  510. // Count the number of X's, taking into account a possible cutoff suffix.
  511. StringRef str = strArg->getString();
  512. unsigned numX = 0;
  513. unsigned n = str.size();
  514. // Take into account the suffix.
  515. unsigned suffix = 0;
  516. if (ArgSuffix.second >= 0) {
  517. const Expr *suffixEx = CE->getArg((unsigned)ArgSuffix.second);
  518. Expr::EvalResult EVResult;
  519. if (!suffixEx->EvaluateAsInt(EVResult, BR.getContext()))
  520. return;
  521. llvm::APSInt Result = EVResult.Val.getInt();
  522. // FIXME: Issue a warning.
  523. if (Result.isNegative())
  524. return;
  525. suffix = (unsigned) Result.getZExtValue();
  526. n = (n > suffix) ? n - suffix : 0;
  527. }
  528. for (unsigned i = 0; i < n; ++i)
  529. if (str[i] == 'X') ++numX;
  530. if (numX >= 6)
  531. return;
  532. // Issue a warning.
  533. PathDiagnosticLocation CELoc =
  534. PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
  535. SmallString<512> buf;
  536. llvm::raw_svector_ostream out(buf);
  537. out << "Call to '" << Name << "' should have at least 6 'X's in the"
  538. " format string to be secure (" << numX << " 'X'";
  539. if (numX != 1)
  540. out << 's';
  541. out << " seen";
  542. if (suffix) {
  543. out << ", " << suffix << " character";
  544. if (suffix > 1)
  545. out << 's';
  546. out << " used as a suffix";
  547. }
  548. out << ')';
  549. BR.EmitBasicReport(AC->getDecl(), filter.checkName_mkstemp,
  550. "Insecure temporary file creation", "Security",
  551. out.str(), CELoc, strArg->getSourceRange());
  552. }
  553. //===----------------------------------------------------------------------===//
  554. // Check: Any use of 'strcpy' is insecure.
  555. //
  556. // CWE-119: Improper Restriction of Operations within
  557. // the Bounds of a Memory Buffer
  558. //===----------------------------------------------------------------------===//
  559. void WalkAST::checkCall_strcpy(const CallExpr *CE, const FunctionDecl *FD) {
  560. if (!filter.check_strcpy)
  561. return;
  562. if (!checkCall_strCommon(CE, FD))
  563. return;
  564. const auto *Target = CE->getArg(0)->IgnoreImpCasts(),
  565. *Source = CE->getArg(1)->IgnoreImpCasts();
  566. if (const auto *Array = dyn_cast<ConstantArrayType>(Target->getType())) {
  567. uint64_t ArraySize = BR.getContext().getTypeSize(Array) / 8;
  568. if (const auto *String = dyn_cast<StringLiteral>(Source)) {
  569. if (ArraySize >= String->getLength() + 1)
  570. return;
  571. }
  572. }
  573. // Issue a warning.
  574. PathDiagnosticLocation CELoc =
  575. PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
  576. BR.EmitBasicReport(AC->getDecl(), filter.checkName_strcpy,
  577. "Potential insecure memory buffer bounds restriction in "
  578. "call 'strcpy'",
  579. "Security",
  580. "Call to function 'strcpy' is insecure as it does not "
  581. "provide bounding of the memory buffer. Replace "
  582. "unbounded copy functions with analogous functions that "
  583. "support length arguments such as 'strlcpy'. CWE-119.",
  584. CELoc, CE->getCallee()->getSourceRange());
  585. }
  586. //===----------------------------------------------------------------------===//
  587. // Check: Any use of 'strcat' is insecure.
  588. //
  589. // CWE-119: Improper Restriction of Operations within
  590. // the Bounds of a Memory Buffer
  591. //===----------------------------------------------------------------------===//
  592. void WalkAST::checkCall_strcat(const CallExpr *CE, const FunctionDecl *FD) {
  593. if (!filter.check_strcpy)
  594. return;
  595. if (!checkCall_strCommon(CE, FD))
  596. return;
  597. // Issue a warning.
  598. PathDiagnosticLocation CELoc =
  599. PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
  600. BR.EmitBasicReport(AC->getDecl(), filter.checkName_strcpy,
  601. "Potential insecure memory buffer bounds restriction in "
  602. "call 'strcat'",
  603. "Security",
  604. "Call to function 'strcat' is insecure as it does not "
  605. "provide bounding of the memory buffer. Replace "
  606. "unbounded copy functions with analogous functions that "
  607. "support length arguments such as 'strlcat'. CWE-119.",
  608. CELoc, CE->getCallee()->getSourceRange());
  609. }
  610. //===----------------------------------------------------------------------===//
  611. // Check: Any use of 'sprintf', 'vsprintf', 'scanf', 'wscanf', 'fscanf',
  612. // 'fwscanf', 'vscanf', 'vwscanf', 'vfscanf', 'vfwscanf', 'sscanf',
  613. // 'swscanf', 'vsscanf', 'vswscanf', 'swprintf', 'snprintf', 'vswprintf',
  614. // 'vsnprintf', 'memcpy', 'memmove', 'strncpy', 'strncat', 'memset'
  615. // is deprecated since C11.
  616. //
  617. // Use of 'sprintf', 'vsprintf', 'scanf', 'wscanf','fscanf',
  618. // 'fwscanf', 'vscanf', 'vwscanf', 'vfscanf', 'vfwscanf', 'sscanf',
  619. // 'swscanf', 'vsscanf', 'vswscanf' without buffer limitations
  620. // is insecure.
  621. //
  622. // CWE-119: Improper Restriction of Operations within
  623. // the Bounds of a Memory Buffer
  624. //===----------------------------------------------------------------------===//
  625. void WalkAST::checkDeprecatedOrUnsafeBufferHandling(const CallExpr *CE,
  626. const FunctionDecl *FD) {
  627. if (!filter.check_DeprecatedOrUnsafeBufferHandling)
  628. return;
  629. if (!BR.getContext().getLangOpts().C11)
  630. return;
  631. // Issue a warning. ArgIndex == -1: Deprecated but not unsafe (has size
  632. // restrictions).
  633. enum { DEPR_ONLY = -1, UNKNOWN_CALL = -2 };
  634. StringRef Name = FD->getIdentifier()->getName();
  635. if (Name.startswith("__builtin_"))
  636. Name = Name.substr(10);
  637. int ArgIndex =
  638. llvm::StringSwitch<int>(Name)
  639. .Cases("scanf", "wscanf", "vscanf", "vwscanf", 0)
  640. .Cases("sprintf", "vsprintf", "fscanf", "fwscanf", "vfscanf",
  641. "vfwscanf", "sscanf", "swscanf", "vsscanf", "vswscanf", 1)
  642. .Cases("swprintf", "snprintf", "vswprintf", "vsnprintf", "memcpy",
  643. "memmove", "memset", "strncpy", "strncat", DEPR_ONLY)
  644. .Default(UNKNOWN_CALL);
  645. assert(ArgIndex != UNKNOWN_CALL && "Unsupported function");
  646. bool BoundsProvided = ArgIndex == DEPR_ONLY;
  647. if (!BoundsProvided) {
  648. // Currently we only handle (not wide) string literals. It is possible to do
  649. // better, either by looking at references to const variables, or by doing
  650. // real flow analysis.
  651. auto FormatString =
  652. dyn_cast<StringLiteral>(CE->getArg(ArgIndex)->IgnoreParenImpCasts());
  653. if (FormatString && !FormatString->getString().contains("%s") &&
  654. !FormatString->getString().contains("%["))
  655. BoundsProvided = true;
  656. }
  657. SmallString<128> Buf1;
  658. SmallString<512> Buf2;
  659. llvm::raw_svector_ostream Out1(Buf1);
  660. llvm::raw_svector_ostream Out2(Buf2);
  661. Out1 << "Potential insecure memory buffer bounds restriction in call '"
  662. << Name << "'";
  663. Out2 << "Call to function '" << Name
  664. << "' is insecure as it does not provide ";
  665. if (!BoundsProvided) {
  666. Out2 << "bounding of the memory buffer or ";
  667. }
  668. Out2 << "security checks introduced "
  669. "in the C11 standard. Replace with analogous functions that "
  670. "support length arguments or provides boundary checks such as '"
  671. << Name << "_s' in case of C11";
  672. PathDiagnosticLocation CELoc =
  673. PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
  674. BR.EmitBasicReport(AC->getDecl(),
  675. filter.checkName_DeprecatedOrUnsafeBufferHandling,
  676. Out1.str(), "Security", Out2.str(), CELoc,
  677. CE->getCallee()->getSourceRange());
  678. }
  679. //===----------------------------------------------------------------------===//
  680. // Common check for str* functions with no bounds parameters.
  681. //===----------------------------------------------------------------------===//
  682. bool WalkAST::checkCall_strCommon(const CallExpr *CE, const FunctionDecl *FD) {
  683. const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>();
  684. if (!FPT)
  685. return false;
  686. // Verify the function takes two arguments, three in the _chk version.
  687. int numArgs = FPT->getNumParams();
  688. if (numArgs != 2 && numArgs != 3)
  689. return false;
  690. // Verify the type for both arguments.
  691. for (int i = 0; i < 2; i++) {
  692. // Verify that the arguments are pointers.
  693. const PointerType *PT = FPT->getParamType(i)->getAs<PointerType>();
  694. if (!PT)
  695. return false;
  696. // Verify that the argument is a 'char*'.
  697. if (PT->getPointeeType().getUnqualifiedType() != BR.getContext().CharTy)
  698. return false;
  699. }
  700. return true;
  701. }
  702. //===----------------------------------------------------------------------===//
  703. // Check: Linear congruent random number generators should not be used
  704. // Originally: <rdar://problem/63371000>
  705. // CWE-338: Use of cryptographically weak prng
  706. //===----------------------------------------------------------------------===//
  707. void WalkAST::checkCall_rand(const CallExpr *CE, const FunctionDecl *FD) {
  708. if (!filter.check_rand || !CheckRand)
  709. return;
  710. const FunctionProtoType *FTP = FD->getType()->getAs<FunctionProtoType>();
  711. if (!FTP)
  712. return;
  713. if (FTP->getNumParams() == 1) {
  714. // Is the argument an 'unsigned short *'?
  715. // (Actually any integer type is allowed.)
  716. const PointerType *PT = FTP->getParamType(0)->getAs<PointerType>();
  717. if (!PT)
  718. return;
  719. if (! PT->getPointeeType()->isIntegralOrUnscopedEnumerationType())
  720. return;
  721. } else if (FTP->getNumParams() != 0)
  722. return;
  723. // Issue a warning.
  724. SmallString<256> buf1;
  725. llvm::raw_svector_ostream os1(buf1);
  726. os1 << '\'' << *FD << "' is a poor random number generator";
  727. SmallString<256> buf2;
  728. llvm::raw_svector_ostream os2(buf2);
  729. os2 << "Function '" << *FD
  730. << "' is obsolete because it implements a poor random number generator."
  731. << " Use 'arc4random' instead";
  732. PathDiagnosticLocation CELoc =
  733. PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
  734. BR.EmitBasicReport(AC->getDecl(), filter.checkName_rand, os1.str(),
  735. "Security", os2.str(), CELoc,
  736. CE->getCallee()->getSourceRange());
  737. }
  738. //===----------------------------------------------------------------------===//
  739. // Check: 'random' should not be used
  740. // Originally: <rdar://problem/63371000>
  741. //===----------------------------------------------------------------------===//
  742. void WalkAST::checkCall_random(const CallExpr *CE, const FunctionDecl *FD) {
  743. if (!CheckRand || !filter.check_rand)
  744. return;
  745. const FunctionProtoType *FTP = FD->getType()->getAs<FunctionProtoType>();
  746. if (!FTP)
  747. return;
  748. // Verify that the function takes no argument.
  749. if (FTP->getNumParams() != 0)
  750. return;
  751. // Issue a warning.
  752. PathDiagnosticLocation CELoc =
  753. PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
  754. BR.EmitBasicReport(AC->getDecl(), filter.checkName_rand,
  755. "'random' is not a secure random number generator",
  756. "Security",
  757. "The 'random' function produces a sequence of values that "
  758. "an adversary may be able to predict. Use 'arc4random' "
  759. "instead", CELoc, CE->getCallee()->getSourceRange());
  760. }
  761. //===----------------------------------------------------------------------===//
  762. // Check: 'vfork' should not be used.
  763. // POS33-C: Do not use vfork().
  764. //===----------------------------------------------------------------------===//
  765. void WalkAST::checkCall_vfork(const CallExpr *CE, const FunctionDecl *FD) {
  766. if (!filter.check_vfork)
  767. return;
  768. // All calls to vfork() are insecure, issue a warning.
  769. PathDiagnosticLocation CELoc =
  770. PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
  771. BR.EmitBasicReport(AC->getDecl(), filter.checkName_vfork,
  772. "Potential insecure implementation-specific behavior in "
  773. "call 'vfork'",
  774. "Security",
  775. "Call to function 'vfork' is insecure as it can lead to "
  776. "denial of service situations in the parent process. "
  777. "Replace calls to vfork with calls to the safer "
  778. "'posix_spawn' function",
  779. CELoc, CE->getCallee()->getSourceRange());
  780. }
  781. //===----------------------------------------------------------------------===//
  782. // Check: '-decodeValueOfObjCType:at:' should not be used.
  783. // It is deprecated in favor of '-decodeValueOfObjCType:at:size:' due to
  784. // likelihood of buffer overflows.
  785. //===----------------------------------------------------------------------===//
  786. void WalkAST::checkMsg_decodeValueOfObjCType(const ObjCMessageExpr *ME) {
  787. if (!filter.check_decodeValueOfObjCType)
  788. return;
  789. // Check availability of the secure alternative:
  790. // iOS 11+, macOS 10.13+, tvOS 11+, and watchOS 4.0+
  791. // FIXME: We probably shouldn't register the check if it's not available.
  792. const TargetInfo &TI = AC->getASTContext().getTargetInfo();
  793. const llvm::Triple &T = TI.getTriple();
  794. const VersionTuple &VT = TI.getPlatformMinVersion();
  795. switch (T.getOS()) {
  796. case llvm::Triple::IOS:
  797. if (VT < VersionTuple(11, 0))
  798. return;
  799. break;
  800. case llvm::Triple::MacOSX:
  801. if (VT < VersionTuple(10, 13))
  802. return;
  803. break;
  804. case llvm::Triple::WatchOS:
  805. if (VT < VersionTuple(4, 0))
  806. return;
  807. break;
  808. case llvm::Triple::TvOS:
  809. if (VT < VersionTuple(11, 0))
  810. return;
  811. break;
  812. default:
  813. return;
  814. }
  815. PathDiagnosticLocation MELoc =
  816. PathDiagnosticLocation::createBegin(ME, BR.getSourceManager(), AC);
  817. BR.EmitBasicReport(
  818. AC->getDecl(), filter.checkName_decodeValueOfObjCType,
  819. "Potential buffer overflow in '-decodeValueOfObjCType:at:'", "Security",
  820. "Deprecated method '-decodeValueOfObjCType:at:' is insecure "
  821. "as it can lead to potential buffer overflows. Use the safer "
  822. "'-decodeValueOfObjCType:at:size:' method.",
  823. MELoc, ME->getSourceRange());
  824. }
  825. //===----------------------------------------------------------------------===//
  826. // Check: Should check whether privileges are dropped successfully.
  827. // Originally: <rdar://problem/6337132>
  828. //===----------------------------------------------------------------------===//
  829. void WalkAST::checkUncheckedReturnValue(CallExpr *CE) {
  830. if (!filter.check_UncheckedReturn)
  831. return;
  832. const FunctionDecl *FD = CE->getDirectCallee();
  833. if (!FD)
  834. return;
  835. if (II_setid[0] == nullptr) {
  836. static const char * const identifiers[num_setids] = {
  837. "setuid", "setgid", "seteuid", "setegid",
  838. "setreuid", "setregid"
  839. };
  840. for (size_t i = 0; i < num_setids; i++)
  841. II_setid[i] = &BR.getContext().Idents.get(identifiers[i]);
  842. }
  843. const IdentifierInfo *id = FD->getIdentifier();
  844. size_t identifierid;
  845. for (identifierid = 0; identifierid < num_setids; identifierid++)
  846. if (id == II_setid[identifierid])
  847. break;
  848. if (identifierid >= num_setids)
  849. return;
  850. const FunctionProtoType *FTP = FD->getType()->getAs<FunctionProtoType>();
  851. if (!FTP)
  852. return;
  853. // Verify that the function takes one or two arguments (depending on
  854. // the function).
  855. if (FTP->getNumParams() != (identifierid < 4 ? 1 : 2))
  856. return;
  857. // The arguments must be integers.
  858. for (unsigned i = 0; i < FTP->getNumParams(); i++)
  859. if (!FTP->getParamType(i)->isIntegralOrUnscopedEnumerationType())
  860. return;
  861. // Issue a warning.
  862. SmallString<256> buf1;
  863. llvm::raw_svector_ostream os1(buf1);
  864. os1 << "Return value is not checked in call to '" << *FD << '\'';
  865. SmallString<256> buf2;
  866. llvm::raw_svector_ostream os2(buf2);
  867. os2 << "The return value from the call to '" << *FD
  868. << "' is not checked. If an error occurs in '" << *FD
  869. << "', the following code may execute with unexpected privileges";
  870. PathDiagnosticLocation CELoc =
  871. PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
  872. BR.EmitBasicReport(AC->getDecl(), filter.checkName_UncheckedReturn, os1.str(),
  873. "Security", os2.str(), CELoc,
  874. CE->getCallee()->getSourceRange());
  875. }
  876. //===----------------------------------------------------------------------===//
  877. // SecuritySyntaxChecker
  878. //===----------------------------------------------------------------------===//
  879. namespace {
  880. class SecuritySyntaxChecker : public Checker<check::ASTCodeBody> {
  881. public:
  882. ChecksFilter filter;
  883. void checkASTCodeBody(const Decl *D, AnalysisManager& mgr,
  884. BugReporter &BR) const {
  885. WalkAST walker(BR, mgr.getAnalysisDeclContext(D), filter);
  886. walker.Visit(D->getBody());
  887. }
  888. };
  889. }
  890. void ento::registerSecuritySyntaxChecker(CheckerManager &mgr) {
  891. mgr.registerChecker<SecuritySyntaxChecker>();
  892. }
  893. bool ento::shouldRegisterSecuritySyntaxChecker(const CheckerManager &mgr) {
  894. return true;
  895. }
  896. #define REGISTER_CHECKER(name) \
  897. void ento::register##name(CheckerManager &mgr) { \
  898. SecuritySyntaxChecker *checker = mgr.getChecker<SecuritySyntaxChecker>(); \
  899. checker->filter.check_##name = true; \
  900. checker->filter.checkName_##name = mgr.getCurrentCheckerName(); \
  901. } \
  902. \
  903. bool ento::shouldRegister##name(const CheckerManager &mgr) { return true; }
  904. REGISTER_CHECKER(bcmp)
  905. REGISTER_CHECKER(bcopy)
  906. REGISTER_CHECKER(bzero)
  907. REGISTER_CHECKER(gets)
  908. REGISTER_CHECKER(getpw)
  909. REGISTER_CHECKER(mkstemp)
  910. REGISTER_CHECKER(mktemp)
  911. REGISTER_CHECKER(strcpy)
  912. REGISTER_CHECKER(rand)
  913. REGISTER_CHECKER(vfork)
  914. REGISTER_CHECKER(FloatLoopCounter)
  915. REGISTER_CHECKER(UncheckedReturn)
  916. REGISTER_CHECKER(DeprecatedOrUnsafeBufferHandling)
  917. REGISTER_CHECKER(decodeValueOfObjCType)