1 //==- CheckSecuritySyntaxOnly.cpp - Basic security checks --------*- C++ -*-==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines a set of flow-insensitive security checks.
12 //===----------------------------------------------------------------------===//
14 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
15 #include "clang/AST/StmtVisitor.h"
16 #include "clang/Analysis/AnalysisDeclContext.h"
17 #include "clang/Basic/TargetInfo.h"
18 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
19 #include "clang/StaticAnalyzer/Core/Checker.h"
20 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/ADT/StringSwitch.h"
23 #include "llvm/Support/raw_ostream.h"
25 using namespace clang;
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 ||
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;
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;
67 class WalkAST : public StmtVisitor<WalkAST> {
69 AnalysisDeclContext* AC;
70 enum { num_setids = 6 };
71 IdentifierInfo *II_setid[num_setids];
74 const ChecksFilter &filter;
77 WalkAST(BugReporter &br, AnalysisDeclContext* ac,
78 const ChecksFilter &f)
79 : BR(br), AC(ac), II_setid(),
80 CheckRand(isArc4RandomAvailable(BR.getContext())),
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); }
89 void VisitChildren(Stmt *S);
92 bool checkCall_strCommon(const CallExpr *CE, const FunctionDecl *FD);
94 typedef void (WalkAST::*FnCheck)(const CallExpr *, const FunctionDecl *);
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);
112 } // end anonymous namespace
114 //===----------------------------------------------------------------------===//
116 //===----------------------------------------------------------------------===//
118 void WalkAST::VisitChildren(Stmt *S) {
119 for (Stmt *Child : S->children())
124 void WalkAST::VisitCallExpr(CallExpr *CE) {
126 const FunctionDecl *FD = CE->getDirectCallee();
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
135 StringRef Name = II->getName();
136 if (Name.startswith("__builtin_"))
137 Name = Name.substr(10);
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)
165 // If the callee isn't defined, it is not of security concern.
166 // Check and evaluate the call.
168 (this->*evalFunction)(CE, FD);
170 // Recurse and check children.
174 void WalkAST::VisitCompoundStmt(CompoundStmt *S) {
175 for (Stmt *Child : S->children())
177 if (CallExpr *CE = dyn_cast<CallExpr>(Child))
178 checkUncheckedReturnValue(CE);
183 void WalkAST::VisitForStmt(ForStmt *FS) {
184 checkLoopConditionForFloat(FS);
186 // Recurse and check children.
190 //===----------------------------------------------------------------------===//
191 // Check: floating point variable used as loop counter.
192 // Originally: <rdar://problem/6336718>
193 // Implements: CERT security coding advisory FLP-30.
194 //===----------------------------------------------------------------------===//
196 static const DeclRefExpr*
197 getIncrementedVar(const Expr *expr, const VarDecl *x, const VarDecl *y) {
198 expr = expr->IgnoreParenCasts();
200 if (const BinaryOperator *B = dyn_cast<BinaryOperator>(expr)) {
201 if (!(B->isAssignmentOp() || B->isCompoundAssignmentOp() ||
202 B->getOpcode() == BO_Comma))
205 if (const DeclRefExpr *lhs = getIncrementedVar(B->getLHS(), x, y))
208 if (const DeclRefExpr *rhs = getIncrementedVar(B->getRHS(), x, y))
214 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(expr)) {
215 const NamedDecl *ND = DR->getDecl();
216 return ND == x || ND == y ? DR : nullptr;
219 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(expr))
220 return U->isIncrementDecrementOp()
221 ? getIncrementedVar(U->getSubExpr(), x, y) : nullptr;
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.
230 void WalkAST::checkLoopConditionForFloat(const ForStmt *FS) {
231 if (!filter.check_FloatLoopCounter)
234 // Does the loop have a condition?
235 const Expr *condition = FS->getCond();
240 // Does the loop have an increment?
241 const Expr *increment = FS->getInc();
246 // Strip away '()' and casts.
247 condition = condition->IgnoreParenCasts();
248 increment = increment->IgnoreParenCasts();
250 // Is the loop condition a comparison?
251 const BinaryOperator *B = dyn_cast<BinaryOperator>(condition);
256 // Is this a comparison?
257 if (!(B->isRelationalOp() || B->isEqualityOp()))
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());
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;
270 if (!drLHS && !drRHS)
273 const VarDecl *vdLHS = drLHS ? dyn_cast<VarDecl>(drLHS->getDecl()) : nullptr;
274 const VarDecl *vdRHS = drRHS ? dyn_cast<VarDecl>(drRHS->getDecl()) : nullptr;
276 if (!vdLHS && !vdRHS)
279 // Does either variable appear in increment?
280 const DeclRefExpr *drInc = getIncrementedVar(increment, vdLHS, vdRHS);
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;
290 SmallVector<SourceRange, 2> ranges;
291 SmallString<256> sbuf;
292 llvm::raw_svector_ostream os(sbuf);
294 os << "Variable '" << drCond->getDecl()->getName()
295 << "' with floating point type '" << drCond->getType().getAsString()
296 << "' should not be used as a loop counter";
298 ranges.push_back(drCond->getSourceRange());
299 ranges.push_back(drInc->getSourceRange());
301 const char *bugType = "Floating point variable used as loop counter";
303 PathDiagnosticLocation FSLoc =
304 PathDiagnosticLocation::createBegin(FS, BR.getSourceManager(), AC);
305 BR.EmitBasicReport(AC->getDecl(), filter.checkName_FloatLoopCounter,
306 bugType, "Security", os.str(),
310 //===----------------------------------------------------------------------===//
311 // Check: Any use of bcmp.
312 // CWE-477: Use of Obsolete Functions
313 // bcmp was deprecated in POSIX.1-2008
314 //===----------------------------------------------------------------------===//
316 void WalkAST::checkCall_bcmp(const CallExpr *CE, const FunctionDecl *FD) {
317 if (!filter.check_bcmp)
320 const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>();
324 // Verify that the function takes three arguments.
325 if (FPT->getNumParams() != 3)
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>();
334 if (PT->getPointeeType().getUnqualifiedType() != BR.getContext().VoidTy)
338 // Verify the third argument type is integer.
339 if (!FPT->getParamType(2)->isIntegralOrUnscopedEnumerationType())
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()'",
348 "The bcmp() function is obsoleted by memcmp().",
349 CELoc, CE->getCallee()->getSourceRange());
352 //===----------------------------------------------------------------------===//
353 // Check: Any use of bcopy.
354 // CWE-477: Use of Obsolete Functions
355 // bcopy was deprecated in POSIX.1-2008
356 //===----------------------------------------------------------------------===//
358 void WalkAST::checkCall_bcopy(const CallExpr *CE, const FunctionDecl *FD) {
359 if (!filter.check_bcopy)
362 const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>();
366 // Verify that the function takes three arguments.
367 if (FPT->getNumParams() != 3)
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>();
376 if (PT->getPointeeType().getUnqualifiedType() != BR.getContext().VoidTy)
380 // Verify the third argument type is integer.
381 if (!FPT->getParamType(2)->isIntegralOrUnscopedEnumerationType())
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()'",
390 "The bcopy() function is obsoleted by memcpy() "
392 CELoc, CE->getCallee()->getSourceRange());
395 //===----------------------------------------------------------------------===//
396 // Check: Any use of bzero.
397 // CWE-477: Use of Obsolete Functions
398 // bzero was deprecated in POSIX.1-2008
399 //===----------------------------------------------------------------------===//
401 void WalkAST::checkCall_bzero(const CallExpr *CE, const FunctionDecl *FD) {
402 if (!filter.check_bzero)
405 const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>();
409 // Verify that the function takes two arguments.
410 if (FPT->getNumParams() != 2)
413 // Verify the first argument type is void*.
414 const PointerType *PT = FPT->getParamType(0)->getAs<PointerType>();
418 if (PT->getPointeeType().getUnqualifiedType() != BR.getContext().VoidTy)
421 // Verify the second argument type is integer.
422 if (!FPT->getParamType(1)->isIntegralOrUnscopedEnumerationType())
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()'",
431 "The bzero() function is obsoleted by memset().",
432 CELoc, CE->getCallee()->getSourceRange());
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 //===----------------------------------------------------------------------===//
443 void WalkAST::checkCall_gets(const CallExpr *CE, const FunctionDecl *FD) {
444 if (!filter.check_gets)
447 const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>();
451 // Verify that the function takes a single argument.
452 if (FPT->getNumParams() != 1)
455 // Is the argument a 'char*'?
456 const PointerType *PT = FPT->getParamType(0)->getAs<PointerType>();
460 if (PT->getPointeeType().getUnqualifiedType() != BR.getContext().CharTy)
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'",
469 "Call to function 'gets' is extremely insecure as it can "
470 "always result in a buffer overflow",
471 CELoc, CE->getCallee()->getSourceRange());
474 //===----------------------------------------------------------------------===//
475 // Check: Any use of 'getpwd' is insecure.
476 // CWE-477: Use of Obsolete Functions
477 //===----------------------------------------------------------------------===//
479 void WalkAST::checkCall_getpw(const CallExpr *CE, const FunctionDecl *FD) {
480 if (!filter.check_getpw)
483 const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>();
487 // Verify that the function takes two arguments.
488 if (FPT->getNumParams() != 2)
491 // Verify the first argument type is integer.
492 if (!FPT->getParamType(0)->isIntegralOrUnscopedEnumerationType())
495 // Verify the second argument type is char*.
496 const PointerType *PT = FPT->getParamType(1)->getAs<PointerType>();
500 if (PT->getPointeeType().getUnqualifiedType() != BR.getContext().CharTy)
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'",
509 "The getpw() function is dangerous as it may overflow the "
510 "provided buffer. It is obsoleted by getpwuid().",
511 CELoc, CE->getCallee()->getSourceRange());
514 //===----------------------------------------------------------------------===//
515 // Check: Any use of 'mktemp' is insecure. It is obsoleted by mkstemp().
516 // CWE-377: Insecure Temporary File
517 //===----------------------------------------------------------------------===//
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);
527 const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>();
531 // Verify that the function takes a single argument.
532 if (FPT->getNumParams() != 1)
535 // Verify that the argument is Pointer Type.
536 const PointerType *PT = FPT->getParamType(0)->getAs<PointerType>();
540 // Verify that the argument is a 'char*'.
541 if (PT->getPointeeType().getUnqualifiedType() != BR.getContext().CharTy)
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'",
550 "Call to function 'mktemp' is insecure as it always "
551 "creates or uses insecure temporary file. Use 'mkstemp' "
553 CELoc, CE->getCallee()->getSourceRange());
557 //===----------------------------------------------------------------------===//
558 // Check: Use of 'mkstemp', 'mktemp', 'mkdtemp' should contain at least 6 X's.
559 //===----------------------------------------------------------------------===//
561 void WalkAST::checkCall_mkstemp(const CallExpr *CE, const FunctionDecl *FD) {
562 if (!filter.check_mkstemp)
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));
574 assert(ArgSuffix.first >= 0 && "Unsupported function");
576 // Check if the number of arguments is consistent with out expectations.
577 unsigned numArgs = CE->getNumArgs();
578 if ((signed) numArgs <= ArgSuffix.first)
581 const StringLiteral *strArg =
582 dyn_cast<StringLiteral>(CE->getArg((unsigned)ArgSuffix.first)
583 ->IgnoreParenImpCasts());
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
588 if (!strArg || strArg->getCharByteWidth() != 1)
591 // Count the number of X's, taking into account a possible cutoff suffix.
592 StringRef str = strArg->getString();
594 unsigned n = str.size();
596 // Take into account the suffix.
598 if (ArgSuffix.second >= 0) {
599 const Expr *suffixEx = CE->getArg((unsigned)ArgSuffix.second);
600 Expr::EvalResult EVResult;
601 if (!suffixEx->EvaluateAsInt(EVResult, BR.getContext()))
603 llvm::APSInt Result = EVResult.Val.getInt();
604 // FIXME: Issue a warning.
605 if (Result.isNegative())
607 suffix = (unsigned) Result.getZExtValue();
608 n = (n > suffix) ? n - suffix : 0;
611 for (unsigned i = 0; i < n; ++i)
612 if (str[i] == 'X') ++numX;
618 PathDiagnosticLocation CELoc =
619 PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
620 SmallString<512> buf;
621 llvm::raw_svector_ostream out(buf);
622 out << "Call to '" << Name << "' should have at least 6 'X's in the"
623 " format string to be secure (" << numX << " 'X'";
628 out << ", " << suffix << " character";
631 out << " used as a suffix";
634 BR.EmitBasicReport(AC->getDecl(), filter.checkName_mkstemp,
635 "Insecure temporary file creation", "Security",
636 out.str(), CELoc, strArg->getSourceRange());
639 //===----------------------------------------------------------------------===//
640 // Check: Any use of 'strcpy' is insecure.
642 // CWE-119: Improper Restriction of Operations within
643 // the Bounds of a Memory Buffer
644 //===----------------------------------------------------------------------===//
645 void WalkAST::checkCall_strcpy(const CallExpr *CE, const FunctionDecl *FD) {
646 if (!filter.check_strcpy)
649 if (!checkCall_strCommon(CE, FD))
652 const auto *Target = CE->getArg(0)->IgnoreImpCasts(),
653 *Source = CE->getArg(1)->IgnoreImpCasts();
655 if (const auto *Array = dyn_cast<ConstantArrayType>(Target->getType())) {
656 uint64_t ArraySize = BR.getContext().getTypeSize(Array) / 8;
657 if (const auto *String = dyn_cast<StringLiteral>(Source)) {
658 if (ArraySize >= String->getLength() + 1)
664 PathDiagnosticLocation CELoc =
665 PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
666 BR.EmitBasicReport(AC->getDecl(), filter.checkName_strcpy,
667 "Potential insecure memory buffer bounds restriction in "
670 "Call to function 'strcpy' is insecure as it does not "
671 "provide bounding of the memory buffer. Replace "
672 "unbounded copy functions with analogous functions that "
673 "support length arguments such as 'strlcpy'. CWE-119.",
674 CELoc, CE->getCallee()->getSourceRange());
677 //===----------------------------------------------------------------------===//
678 // Check: Any use of 'strcat' is insecure.
680 // CWE-119: Improper Restriction of Operations within
681 // the Bounds of a Memory Buffer
682 //===----------------------------------------------------------------------===//
683 void WalkAST::checkCall_strcat(const CallExpr *CE, const FunctionDecl *FD) {
684 if (!filter.check_strcpy)
687 if (!checkCall_strCommon(CE, FD))
691 PathDiagnosticLocation CELoc =
692 PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
693 BR.EmitBasicReport(AC->getDecl(), filter.checkName_strcpy,
694 "Potential insecure memory buffer bounds restriction in "
697 "Call to function 'strcat' is insecure as it does not "
698 "provide bounding of the memory buffer. Replace "
699 "unbounded copy functions with analogous functions that "
700 "support length arguments such as 'strlcat'. CWE-119.",
701 CELoc, CE->getCallee()->getSourceRange());
704 //===----------------------------------------------------------------------===//
705 // Common check for str* functions with no bounds parameters.
706 //===----------------------------------------------------------------------===//
707 bool WalkAST::checkCall_strCommon(const CallExpr *CE, const FunctionDecl *FD) {
708 const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>();
712 // Verify the function takes two arguments, three in the _chk version.
713 int numArgs = FPT->getNumParams();
714 if (numArgs != 2 && numArgs != 3)
717 // Verify the type for both arguments.
718 for (int i = 0; i < 2; i++) {
719 // Verify that the arguments are pointers.
720 const PointerType *PT = FPT->getParamType(i)->getAs<PointerType>();
724 // Verify that the argument is a 'char*'.
725 if (PT->getPointeeType().getUnqualifiedType() != BR.getContext().CharTy)
732 //===----------------------------------------------------------------------===//
733 // Check: Linear congruent random number generators should not be used
734 // Originally: <rdar://problem/63371000>
735 // CWE-338: Use of cryptographically weak prng
736 //===----------------------------------------------------------------------===//
738 void WalkAST::checkCall_rand(const CallExpr *CE, const FunctionDecl *FD) {
739 if (!filter.check_rand || !CheckRand)
742 const FunctionProtoType *FTP = FD->getType()->getAs<FunctionProtoType>();
746 if (FTP->getNumParams() == 1) {
747 // Is the argument an 'unsigned short *'?
748 // (Actually any integer type is allowed.)
749 const PointerType *PT = FTP->getParamType(0)->getAs<PointerType>();
753 if (! PT->getPointeeType()->isIntegralOrUnscopedEnumerationType())
755 } else if (FTP->getNumParams() != 0)
759 SmallString<256> buf1;
760 llvm::raw_svector_ostream os1(buf1);
761 os1 << '\'' << *FD << "' is a poor random number generator";
763 SmallString<256> buf2;
764 llvm::raw_svector_ostream os2(buf2);
765 os2 << "Function '" << *FD
766 << "' is obsolete because it implements a poor random number generator."
767 << " Use 'arc4random' instead";
769 PathDiagnosticLocation CELoc =
770 PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
771 BR.EmitBasicReport(AC->getDecl(), filter.checkName_rand, os1.str(),
772 "Security", os2.str(), CELoc,
773 CE->getCallee()->getSourceRange());
776 //===----------------------------------------------------------------------===//
777 // Check: 'random' should not be used
778 // Originally: <rdar://problem/63371000>
779 //===----------------------------------------------------------------------===//
781 void WalkAST::checkCall_random(const CallExpr *CE, const FunctionDecl *FD) {
782 if (!CheckRand || !filter.check_rand)
785 const FunctionProtoType *FTP = FD->getType()->getAs<FunctionProtoType>();
789 // Verify that the function takes no argument.
790 if (FTP->getNumParams() != 0)
794 PathDiagnosticLocation CELoc =
795 PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
796 BR.EmitBasicReport(AC->getDecl(), filter.checkName_rand,
797 "'random' is not a secure random number generator",
799 "The 'random' function produces a sequence of values that "
800 "an adversary may be able to predict. Use 'arc4random' "
801 "instead", CELoc, CE->getCallee()->getSourceRange());
804 //===----------------------------------------------------------------------===//
805 // Check: 'vfork' should not be used.
806 // POS33-C: Do not use vfork().
807 //===----------------------------------------------------------------------===//
809 void WalkAST::checkCall_vfork(const CallExpr *CE, const FunctionDecl *FD) {
810 if (!filter.check_vfork)
813 // All calls to vfork() are insecure, issue a warning.
814 PathDiagnosticLocation CELoc =
815 PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
816 BR.EmitBasicReport(AC->getDecl(), filter.checkName_vfork,
817 "Potential insecure implementation-specific behavior in "
820 "Call to function 'vfork' is insecure as it can lead to "
821 "denial of service situations in the parent process. "
822 "Replace calls to vfork with calls to the safer "
823 "'posix_spawn' function",
824 CELoc, CE->getCallee()->getSourceRange());
827 //===----------------------------------------------------------------------===//
828 // Check: Should check whether privileges are dropped successfully.
829 // Originally: <rdar://problem/6337132>
830 //===----------------------------------------------------------------------===//
832 void WalkAST::checkUncheckedReturnValue(CallExpr *CE) {
833 if (!filter.check_UncheckedReturn)
836 const FunctionDecl *FD = CE->getDirectCallee();
840 if (II_setid[0] == nullptr) {
841 static const char * const identifiers[num_setids] = {
842 "setuid", "setgid", "seteuid", "setegid",
843 "setreuid", "setregid"
846 for (size_t i = 0; i < num_setids; i++)
847 II_setid[i] = &BR.getContext().Idents.get(identifiers[i]);
850 const IdentifierInfo *id = FD->getIdentifier();
853 for (identifierid = 0; identifierid < num_setids; identifierid++)
854 if (id == II_setid[identifierid])
857 if (identifierid >= num_setids)
860 const FunctionProtoType *FTP = FD->getType()->getAs<FunctionProtoType>();
864 // Verify that the function takes one or two arguments (depending on
866 if (FTP->getNumParams() != (identifierid < 4 ? 1 : 2))
869 // The arguments must be integers.
870 for (unsigned i = 0; i < FTP->getNumParams(); i++)
871 if (!FTP->getParamType(i)->isIntegralOrUnscopedEnumerationType())
875 SmallString<256> buf1;
876 llvm::raw_svector_ostream os1(buf1);
877 os1 << "Return value is not checked in call to '" << *FD << '\'';
879 SmallString<256> buf2;
880 llvm::raw_svector_ostream os2(buf2);
881 os2 << "The return value from the call to '" << *FD
882 << "' is not checked. If an error occurs in '" << *FD
883 << "', the following code may execute with unexpected privileges";
885 PathDiagnosticLocation CELoc =
886 PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
887 BR.EmitBasicReport(AC->getDecl(), filter.checkName_UncheckedReturn, os1.str(),
888 "Security", os2.str(), CELoc,
889 CE->getCallee()->getSourceRange());
892 //===----------------------------------------------------------------------===//
893 // SecuritySyntaxChecker
894 //===----------------------------------------------------------------------===//
897 class SecuritySyntaxChecker : public Checker<check::ASTCodeBody> {
901 void checkASTCodeBody(const Decl *D, AnalysisManager& mgr,
902 BugReporter &BR) const {
903 WalkAST walker(BR, mgr.getAnalysisDeclContext(D), filter);
904 walker.Visit(D->getBody());
909 #define REGISTER_CHECKER(name) \
910 void ento::register##name(CheckerManager &mgr) { \
911 SecuritySyntaxChecker *checker = \
912 mgr.registerChecker<SecuritySyntaxChecker>(); \
913 checker->filter.check_##name = true; \
914 checker->filter.checkName_##name = mgr.getCurrentCheckName(); \
917 REGISTER_CHECKER(bcmp)
918 REGISTER_CHECKER(bcopy)
919 REGISTER_CHECKER(bzero)
920 REGISTER_CHECKER(gets)
921 REGISTER_CHECKER(getpw)
922 REGISTER_CHECKER(mkstemp)
923 REGISTER_CHECKER(mktemp)
924 REGISTER_CHECKER(strcpy)
925 REGISTER_CHECKER(rand)
926 REGISTER_CHECKER(vfork)
927 REGISTER_CHECKER(FloatLoopCounter)
928 REGISTER_CHECKER(UncheckedReturn)