CheckSecuritySyntaxOnly.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  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 "clang/Basic/TargetInfo.h"
  14. #include "clang/StaticAnalyzer/BugReporter/BugReporter.h"
  15. #include "clang/StaticAnalyzer/Checkers/LocalCheckers.h"
  16. #include "clang/AST/StmtVisitor.h"
  17. #include "llvm/Support/raw_ostream.h"
  18. using namespace clang;
  19. using namespace ento;
  20. static bool isArc4RandomAvailable(const ASTContext &Ctx) {
  21. const llvm::Triple &T = Ctx.Target.getTriple();
  22. return T.getVendor() == llvm::Triple::Apple ||
  23. T.getOS() == llvm::Triple::FreeBSD ||
  24. T.getOS() == llvm::Triple::NetBSD ||
  25. T.getOS() == llvm::Triple::OpenBSD ||
  26. T.getOS() == llvm::Triple::DragonFly;
  27. }
  28. namespace {
  29. class WalkAST : public StmtVisitor<WalkAST> {
  30. BugReporter &BR;
  31. IdentifierInfo *II_gets;
  32. IdentifierInfo *II_getpw;
  33. IdentifierInfo *II_mktemp;
  34. enum { num_rands = 9 };
  35. IdentifierInfo *II_rand[num_rands];
  36. IdentifierInfo *II_random;
  37. enum { num_setids = 6 };
  38. IdentifierInfo *II_setid[num_setids];
  39. const bool CheckRand;
  40. public:
  41. WalkAST(BugReporter &br) : BR(br),
  42. II_gets(0), II_getpw(0), II_mktemp(0),
  43. II_rand(), II_random(0), II_setid(),
  44. CheckRand(isArc4RandomAvailable(BR.getContext())) {}
  45. // Statement visitor methods.
  46. void VisitCallExpr(CallExpr *CE);
  47. void VisitForStmt(ForStmt *S);
  48. void VisitCompoundStmt (CompoundStmt *S);
  49. void VisitStmt(Stmt *S) { VisitChildren(S); }
  50. void VisitChildren(Stmt *S);
  51. // Helpers.
  52. IdentifierInfo *GetIdentifier(IdentifierInfo *& II, const char *str);
  53. // Checker-specific methods.
  54. void CheckLoopConditionForFloat(const ForStmt *FS);
  55. void CheckCall_gets(const CallExpr *CE, const FunctionDecl *FD);
  56. void CheckCall_getpw(const CallExpr *CE, const FunctionDecl *FD);
  57. void CheckCall_mktemp(const CallExpr *CE, const FunctionDecl *FD);
  58. void CheckCall_rand(const CallExpr *CE, const FunctionDecl *FD);
  59. void CheckCall_random(const CallExpr *CE, const FunctionDecl *FD);
  60. void CheckUncheckedReturnValue(CallExpr *CE);
  61. };
  62. } // end anonymous namespace
  63. //===----------------------------------------------------------------------===//
  64. // Helper methods.
  65. //===----------------------------------------------------------------------===//
  66. IdentifierInfo *WalkAST::GetIdentifier(IdentifierInfo *& II, const char *str) {
  67. if (!II)
  68. II = &BR.getContext().Idents.get(str);
  69. return II;
  70. }
  71. //===----------------------------------------------------------------------===//
  72. // AST walking.
  73. //===----------------------------------------------------------------------===//
  74. void WalkAST::VisitChildren(Stmt *S) {
  75. for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
  76. if (Stmt *child = *I)
  77. Visit(child);
  78. }
  79. void WalkAST::VisitCallExpr(CallExpr *CE) {
  80. if (const FunctionDecl *FD = CE->getDirectCallee()) {
  81. CheckCall_gets(CE, FD);
  82. CheckCall_getpw(CE, FD);
  83. CheckCall_mktemp(CE, FD);
  84. if (CheckRand) {
  85. CheckCall_rand(CE, FD);
  86. CheckCall_random(CE, FD);
  87. }
  88. }
  89. // Recurse and check children.
  90. VisitChildren(CE);
  91. }
  92. void WalkAST::VisitCompoundStmt(CompoundStmt *S) {
  93. for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
  94. if (Stmt *child = *I) {
  95. if (CallExpr *CE = dyn_cast<CallExpr>(child))
  96. CheckUncheckedReturnValue(CE);
  97. Visit(child);
  98. }
  99. }
  100. void WalkAST::VisitForStmt(ForStmt *FS) {
  101. CheckLoopConditionForFloat(FS);
  102. // Recurse and check children.
  103. VisitChildren(FS);
  104. }
  105. //===----------------------------------------------------------------------===//
  106. // Check: floating poing variable used as loop counter.
  107. // Originally: <rdar://problem/6336718>
  108. // Implements: CERT security coding advisory FLP-30.
  109. //===----------------------------------------------------------------------===//
  110. static const DeclRefExpr*
  111. GetIncrementedVar(const Expr *expr, const VarDecl *x, const VarDecl *y) {
  112. expr = expr->IgnoreParenCasts();
  113. if (const BinaryOperator *B = dyn_cast<BinaryOperator>(expr)) {
  114. if (!(B->isAssignmentOp() || B->isCompoundAssignmentOp() ||
  115. B->getOpcode() == BO_Comma))
  116. return NULL;
  117. if (const DeclRefExpr *lhs = GetIncrementedVar(B->getLHS(), x, y))
  118. return lhs;
  119. if (const DeclRefExpr *rhs = GetIncrementedVar(B->getRHS(), x, y))
  120. return rhs;
  121. return NULL;
  122. }
  123. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(expr)) {
  124. const NamedDecl *ND = DR->getDecl();
  125. return ND == x || ND == y ? DR : NULL;
  126. }
  127. if (const UnaryOperator *U = dyn_cast<UnaryOperator>(expr))
  128. return U->isIncrementDecrementOp()
  129. ? GetIncrementedVar(U->getSubExpr(), x, y) : NULL;
  130. return NULL;
  131. }
  132. /// CheckLoopConditionForFloat - This check looks for 'for' statements that
  133. /// use a floating point variable as a loop counter.
  134. /// CERT: FLP30-C, FLP30-CPP.
  135. ///
  136. void WalkAST::CheckLoopConditionForFloat(const ForStmt *FS) {
  137. // Does the loop have a condition?
  138. const Expr *condition = FS->getCond();
  139. if (!condition)
  140. return;
  141. // Does the loop have an increment?
  142. const Expr *increment = FS->getInc();
  143. if (!increment)
  144. return;
  145. // Strip away '()' and casts.
  146. condition = condition->IgnoreParenCasts();
  147. increment = increment->IgnoreParenCasts();
  148. // Is the loop condition a comparison?
  149. const BinaryOperator *B = dyn_cast<BinaryOperator>(condition);
  150. if (!B)
  151. return;
  152. // Is this a comparison?
  153. if (!(B->isRelationalOp() || B->isEqualityOp()))
  154. return;
  155. // Are we comparing variables?
  156. const DeclRefExpr *drLHS =
  157. dyn_cast<DeclRefExpr>(B->getLHS()->IgnoreParenLValueCasts());
  158. const DeclRefExpr *drRHS =
  159. dyn_cast<DeclRefExpr>(B->getRHS()->IgnoreParenLValueCasts());
  160. // Does at least one of the variables have a floating point type?
  161. drLHS = drLHS && drLHS->getType()->isRealFloatingType() ? drLHS : NULL;
  162. drRHS = drRHS && drRHS->getType()->isRealFloatingType() ? drRHS : NULL;
  163. if (!drLHS && !drRHS)
  164. return;
  165. const VarDecl *vdLHS = drLHS ? dyn_cast<VarDecl>(drLHS->getDecl()) : NULL;
  166. const VarDecl *vdRHS = drRHS ? dyn_cast<VarDecl>(drRHS->getDecl()) : NULL;
  167. if (!vdLHS && !vdRHS)
  168. return;
  169. // Does either variable appear in increment?
  170. const DeclRefExpr *drInc = GetIncrementedVar(increment, vdLHS, vdRHS);
  171. if (!drInc)
  172. return;
  173. // Emit the error. First figure out which DeclRefExpr in the condition
  174. // referenced the compared variable.
  175. const DeclRefExpr *drCond = vdLHS == drInc->getDecl() ? drLHS : drRHS;
  176. llvm::SmallVector<SourceRange, 2> ranges;
  177. llvm::SmallString<256> sbuf;
  178. llvm::raw_svector_ostream os(sbuf);
  179. os << "Variable '" << drCond->getDecl()->getName()
  180. << "' with floating point type '" << drCond->getType().getAsString()
  181. << "' should not be used as a loop counter";
  182. ranges.push_back(drCond->getSourceRange());
  183. ranges.push_back(drInc->getSourceRange());
  184. const char *bugType = "Floating point variable used as loop counter";
  185. BR.EmitBasicReport(bugType, "Security", os.str(),
  186. FS->getLocStart(), ranges.data(), ranges.size());
  187. }
  188. //===----------------------------------------------------------------------===//
  189. // Check: Any use of 'gets' is insecure.
  190. // Originally: <rdar://problem/6335715>
  191. // Implements (part of): 300-BSI (buildsecurityin.us-cert.gov)
  192. // CWE-242: Use of Inherently Dangerous Function
  193. //===----------------------------------------------------------------------===//
  194. void WalkAST::CheckCall_gets(const CallExpr *CE, const FunctionDecl *FD) {
  195. if (FD->getIdentifier() != GetIdentifier(II_gets, "gets"))
  196. return;
  197. const FunctionProtoType *FPT
  198. = dyn_cast<FunctionProtoType>(FD->getType().IgnoreParens());
  199. if (!FPT)
  200. return;
  201. // Verify that the function takes a single argument.
  202. if (FPT->getNumArgs() != 1)
  203. return;
  204. // Is the argument a 'char*'?
  205. const PointerType *PT = dyn_cast<PointerType>(FPT->getArgType(0));
  206. if (!PT)
  207. return;
  208. if (PT->getPointeeType().getUnqualifiedType() != BR.getContext().CharTy)
  209. return;
  210. // Issue a warning.
  211. SourceRange R = CE->getCallee()->getSourceRange();
  212. BR.EmitBasicReport("Potential buffer overflow in call to 'gets'",
  213. "Security",
  214. "Call to function 'gets' is extremely insecure as it can "
  215. "always result in a buffer overflow",
  216. CE->getLocStart(), &R, 1);
  217. }
  218. //===----------------------------------------------------------------------===//
  219. // Check: Any use of 'getpwd' is insecure.
  220. // CWE-477: Use of Obsolete Functions
  221. //===----------------------------------------------------------------------===//
  222. void WalkAST::CheckCall_getpw(const CallExpr *CE, const FunctionDecl *FD) {
  223. if (FD->getIdentifier() != GetIdentifier(II_getpw, "getpw"))
  224. return;
  225. const FunctionProtoType *FPT
  226. = dyn_cast<FunctionProtoType>(FD->getType().IgnoreParens());
  227. if (!FPT)
  228. return;
  229. // Verify that the function takes two arguments.
  230. if (FPT->getNumArgs() != 2)
  231. return;
  232. // Verify the first argument type is integer.
  233. if (!FPT->getArgType(0)->isIntegerType())
  234. return;
  235. // Verify the second argument type is char*.
  236. const PointerType *PT = dyn_cast<PointerType>(FPT->getArgType(1));
  237. if (!PT)
  238. return;
  239. if (PT->getPointeeType().getUnqualifiedType() != BR.getContext().CharTy)
  240. return;
  241. // Issue a warning.
  242. SourceRange R = CE->getCallee()->getSourceRange();
  243. BR.EmitBasicReport("Potential buffer overflow in call to 'getpw'",
  244. "Security",
  245. "The getpw() function is dangerous as it may overflow the "
  246. "provided buffer. It is obsoleted by getpwuid().",
  247. CE->getLocStart(), &R, 1);
  248. }
  249. //===----------------------------------------------------------------------===//
  250. // Check: Any use of 'mktemp' is insecure.It is obsoleted by mkstemp().
  251. // CWE-377: Insecure Temporary File
  252. //===----------------------------------------------------------------------===//
  253. void WalkAST::CheckCall_mktemp(const CallExpr *CE, const FunctionDecl *FD) {
  254. if (FD->getIdentifier() != GetIdentifier(II_mktemp, "mktemp"))
  255. return;
  256. const FunctionProtoType *FPT
  257. = dyn_cast<FunctionProtoType>(FD->getType().IgnoreParens());
  258. if(!FPT)
  259. return;
  260. // Verify that the funcion takes a single argument.
  261. if (FPT->getNumArgs() != 1)
  262. return;
  263. // Verify that the argument is Pointer Type.
  264. const PointerType *PT = dyn_cast<PointerType>(FPT->getArgType(0));
  265. if (!PT)
  266. return;
  267. // Verify that the argument is a 'char*'.
  268. if (PT->getPointeeType().getUnqualifiedType() != BR.getContext().CharTy)
  269. return;
  270. // Issue a waring.
  271. SourceRange R = CE->getCallee()->getSourceRange();
  272. BR.EmitBasicReport("Potential insecure temporary file in call 'mktemp'",
  273. "Security",
  274. "Call to function 'mktemp' is insecure as it always "
  275. "creates or uses insecure temporary file. Use 'mkstemp' instead",
  276. CE->getLocStart(), &R, 1);
  277. }
  278. //===----------------------------------------------------------------------===//
  279. // Check: Linear congruent random number generators should not be used
  280. // Originally: <rdar://problem/63371000>
  281. // CWE-338: Use of cryptographically weak prng
  282. //===----------------------------------------------------------------------===//
  283. void WalkAST::CheckCall_rand(const CallExpr *CE, const FunctionDecl *FD) {
  284. if (II_rand[0] == NULL) {
  285. // This check applies to these functions
  286. static const char * const identifiers[num_rands] = {
  287. "drand48", "erand48", "jrand48", "lrand48", "mrand48", "nrand48",
  288. "lcong48",
  289. "rand", "rand_r"
  290. };
  291. for (size_t i = 0; i < num_rands; i++)
  292. II_rand[i] = &BR.getContext().Idents.get(identifiers[i]);
  293. }
  294. const IdentifierInfo *id = FD->getIdentifier();
  295. size_t identifierid;
  296. for (identifierid = 0; identifierid < num_rands; identifierid++)
  297. if (id == II_rand[identifierid])
  298. break;
  299. if (identifierid >= num_rands)
  300. return;
  301. const FunctionProtoType *FTP
  302. = dyn_cast<FunctionProtoType>(FD->getType().IgnoreParens());
  303. if (!FTP)
  304. return;
  305. if (FTP->getNumArgs() == 1) {
  306. // Is the argument an 'unsigned short *'?
  307. // (Actually any integer type is allowed.)
  308. const PointerType *PT = dyn_cast<PointerType>(FTP->getArgType(0));
  309. if (!PT)
  310. return;
  311. if (! PT->getPointeeType()->isIntegerType())
  312. return;
  313. }
  314. else if (FTP->getNumArgs() != 0)
  315. return;
  316. // Issue a warning.
  317. llvm::SmallString<256> buf1;
  318. llvm::raw_svector_ostream os1(buf1);
  319. os1 << '\'' << FD << "' is a poor random number generator";
  320. llvm::SmallString<256> buf2;
  321. llvm::raw_svector_ostream os2(buf2);
  322. os2 << "Function '" << FD
  323. << "' is obsolete because it implements a poor random number generator."
  324. << " Use 'arc4random' instead";
  325. SourceRange R = CE->getCallee()->getSourceRange();
  326. BR.EmitBasicReport(os1.str(), "Security", os2.str(),CE->getLocStart(), &R, 1);
  327. }
  328. //===----------------------------------------------------------------------===//
  329. // Check: 'random' should not be used
  330. // Originally: <rdar://problem/63371000>
  331. //===----------------------------------------------------------------------===//
  332. void WalkAST::CheckCall_random(const CallExpr *CE, const FunctionDecl *FD) {
  333. if (FD->getIdentifier() != GetIdentifier(II_random, "random"))
  334. return;
  335. const FunctionProtoType *FTP
  336. = dyn_cast<FunctionProtoType>(FD->getType().IgnoreParens());
  337. if (!FTP)
  338. return;
  339. // Verify that the function takes no argument.
  340. if (FTP->getNumArgs() != 0)
  341. return;
  342. // Issue a warning.
  343. SourceRange R = CE->getCallee()->getSourceRange();
  344. BR.EmitBasicReport("'random' is not a secure random number generator",
  345. "Security",
  346. "The 'random' function produces a sequence of values that "
  347. "an adversary may be able to predict. Use 'arc4random' "
  348. "instead", CE->getLocStart(), &R, 1);
  349. }
  350. //===----------------------------------------------------------------------===//
  351. // Check: Should check whether privileges are dropped successfully.
  352. // Originally: <rdar://problem/6337132>
  353. //===----------------------------------------------------------------------===//
  354. void WalkAST::CheckUncheckedReturnValue(CallExpr *CE) {
  355. const FunctionDecl *FD = CE->getDirectCallee();
  356. if (!FD)
  357. return;
  358. if (II_setid[0] == NULL) {
  359. static const char * const identifiers[num_setids] = {
  360. "setuid", "setgid", "seteuid", "setegid",
  361. "setreuid", "setregid"
  362. };
  363. for (size_t i = 0; i < num_setids; i++)
  364. II_setid[i] = &BR.getContext().Idents.get(identifiers[i]);
  365. }
  366. const IdentifierInfo *id = FD->getIdentifier();
  367. size_t identifierid;
  368. for (identifierid = 0; identifierid < num_setids; identifierid++)
  369. if (id == II_setid[identifierid])
  370. break;
  371. if (identifierid >= num_setids)
  372. return;
  373. const FunctionProtoType *FTP
  374. = dyn_cast<FunctionProtoType>(FD->getType().IgnoreParens());
  375. if (!FTP)
  376. return;
  377. // Verify that the function takes one or two arguments (depending on
  378. // the function).
  379. if (FTP->getNumArgs() != (identifierid < 4 ? 1 : 2))
  380. return;
  381. // The arguments must be integers.
  382. for (unsigned i = 0; i < FTP->getNumArgs(); i++)
  383. if (! FTP->getArgType(i)->isIntegerType())
  384. return;
  385. // Issue a warning.
  386. llvm::SmallString<256> buf1;
  387. llvm::raw_svector_ostream os1(buf1);
  388. os1 << "Return value is not checked in call to '" << FD << '\'';
  389. llvm::SmallString<256> buf2;
  390. llvm::raw_svector_ostream os2(buf2);
  391. os2 << "The return value from the call to '" << FD
  392. << "' is not checked. If an error occurs in '" << FD
  393. << "', the following code may execute with unexpected privileges";
  394. SourceRange R = CE->getCallee()->getSourceRange();
  395. BR.EmitBasicReport(os1.str(), "Security", os2.str(),CE->getLocStart(), &R, 1);
  396. }
  397. //===----------------------------------------------------------------------===//
  398. // Entry point for check.
  399. //===----------------------------------------------------------------------===//
  400. void ento::CheckSecuritySyntaxOnly(const Decl *D, BugReporter &BR) {
  401. WalkAST walker(BR);
  402. walker.Visit(D->getBody());
  403. }