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