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 "ClangSACheckers.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 ||
32 T.getOS() == llvm::Triple::FreeBSD ||
33 T.getOS() == llvm::Triple::NetBSD ||
34 T.getOS() == llvm::Triple::OpenBSD ||
35 T.getOS() == llvm::Triple::DragonFly;
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 poing 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);
601 if (!suffixEx->EvaluateAsInt(Result, BR.getContext()))
603 // FIXME: Issue a warning.
604 if (Result.isNegative())
606 suffix = (unsigned) Result.getZExtValue();
607 n = (n > suffix) ? n - suffix : 0;
610 for (unsigned i = 0; i < n; ++i)
611 if (str[i] == 'X') ++numX;
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'";
627 out << ", " << suffix << " character";
630 out << " used as a suffix";
633 BR.EmitBasicReport(AC->getDecl(), filter.checkName_mkstemp,
634 "Insecure temporary file creation", "Security",
635 out.str(), CELoc, strArg->getSourceRange());
638 //===----------------------------------------------------------------------===//
639 // Check: Any use of 'strcpy' is insecure.
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)
648 if (!checkCall_strCommon(CE, FD))
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)
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 "
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());
676 //===----------------------------------------------------------------------===//
677 // Check: Any use of 'strcat' is insecure.
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)
686 if (!checkCall_strCommon(CE, FD))
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 "
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());
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>();
711 // Verify the function takes two arguments, three in the _chk version.
712 int numArgs = FPT->getNumParams();
713 if (numArgs != 2 && numArgs != 3)
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>();
723 // Verify that the argument is a 'char*'.
724 if (PT->getPointeeType().getUnqualifiedType() != BR.getContext().CharTy)
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 //===----------------------------------------------------------------------===//
737 void WalkAST::checkCall_rand(const CallExpr *CE, const FunctionDecl *FD) {
738 if (!filter.check_rand || !CheckRand)
741 const FunctionProtoType *FTP = FD->getType()->getAs<FunctionProtoType>();
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>();
752 if (! PT->getPointeeType()->isIntegralOrUnscopedEnumerationType())
754 } else if (FTP->getNumParams() != 0)
758 SmallString<256> buf1;
759 llvm::raw_svector_ostream os1(buf1);
760 os1 << '\'' << *FD << "' is a poor random number generator";
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";
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());
775 //===----------------------------------------------------------------------===//
776 // Check: 'random' should not be used
777 // Originally: <rdar://problem/63371000>
778 //===----------------------------------------------------------------------===//
780 void WalkAST::checkCall_random(const CallExpr *CE, const FunctionDecl *FD) {
781 if (!CheckRand || !filter.check_rand)
784 const FunctionProtoType *FTP = FD->getType()->getAs<FunctionProtoType>();
788 // Verify that the function takes no argument.
789 if (FTP->getNumParams() != 0)
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",
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());
803 //===----------------------------------------------------------------------===//
804 // Check: 'vfork' should not be used.
805 // POS33-C: Do not use vfork().
806 //===----------------------------------------------------------------------===//
808 void WalkAST::checkCall_vfork(const CallExpr *CE, const FunctionDecl *FD) {
809 if (!filter.check_vfork)
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 "
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());
826 //===----------------------------------------------------------------------===//
827 // Check: Should check whether privileges are dropped successfully.
828 // Originally: <rdar://problem/6337132>
829 //===----------------------------------------------------------------------===//
831 void WalkAST::checkUncheckedReturnValue(CallExpr *CE) {
832 if (!filter.check_UncheckedReturn)
835 const FunctionDecl *FD = CE->getDirectCallee();
839 if (II_setid[0] == nullptr) {
840 static const char * const identifiers[num_setids] = {
841 "setuid", "setgid", "seteuid", "setegid",
842 "setreuid", "setregid"
845 for (size_t i = 0; i < num_setids; i++)
846 II_setid[i] = &BR.getContext().Idents.get(identifiers[i]);
849 const IdentifierInfo *id = FD->getIdentifier();
852 for (identifierid = 0; identifierid < num_setids; identifierid++)
853 if (id == II_setid[identifierid])
856 if (identifierid >= num_setids)
859 const FunctionProtoType *FTP = FD->getType()->getAs<FunctionProtoType>();
863 // Verify that the function takes one or two arguments (depending on
865 if (FTP->getNumParams() != (identifierid < 4 ? 1 : 2))
868 // The arguments must be integers.
869 for (unsigned i = 0; i < FTP->getNumParams(); i++)
870 if (!FTP->getParamType(i)->isIntegralOrUnscopedEnumerationType())
874 SmallString<256> buf1;
875 llvm::raw_svector_ostream os1(buf1);
876 os1 << "Return value is not checked in call to '" << *FD << '\'';
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";
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());
891 //===----------------------------------------------------------------------===//
892 // SecuritySyntaxChecker
893 //===----------------------------------------------------------------------===//
896 class SecuritySyntaxChecker : public Checker<check::ASTCodeBody> {
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());
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(); \
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)