xref: /llvm-project/clang/lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp (revision 8fd74ebfc03317feac43f513cb9e7d45e9215d12)
1 //==- CheckSecuritySyntaxOnly.cpp - Basic security checks --------*- C++ -*-==//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file defines a set of flow-insensitive security checks.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
14 #include "clang/AST/StmtVisitor.h"
15 #include "clang/Analysis/AnalysisDeclContext.h"
16 #include "clang/Basic/TargetInfo.h"
17 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
18 #include "clang/StaticAnalyzer/Core/Checker.h"
19 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/ADT/StringSwitch.h"
22 #include "llvm/Support/raw_ostream.h"
23 
24 using namespace clang;
25 using namespace ento;
26 
27 static bool isArc4RandomAvailable(const ASTContext &Ctx) {
28   const llvm::Triple &T = Ctx.getTargetInfo().getTriple();
29   return T.getVendor() == llvm::Triple::Apple ||
30          T.getOS() == llvm::Triple::CloudABI ||
31          T.isOSFreeBSD() ||
32          T.isOSNetBSD() ||
33          T.isOSOpenBSD() ||
34          T.isOSDragonFly();
35 }
36 
37 namespace {
38 struct ChecksFilter {
39   DefaultBool check_bcmp;
40   DefaultBool check_bcopy;
41   DefaultBool check_bzero;
42   DefaultBool check_gets;
43   DefaultBool check_getpw;
44   DefaultBool check_mktemp;
45   DefaultBool check_mkstemp;
46   DefaultBool check_strcpy;
47   DefaultBool check_rand;
48   DefaultBool check_vfork;
49   DefaultBool check_FloatLoopCounter;
50   DefaultBool check_UncheckedReturn;
51 
52   CheckName checkName_bcmp;
53   CheckName checkName_bcopy;
54   CheckName checkName_bzero;
55   CheckName checkName_gets;
56   CheckName checkName_getpw;
57   CheckName checkName_mktemp;
58   CheckName checkName_mkstemp;
59   CheckName checkName_strcpy;
60   CheckName checkName_rand;
61   CheckName checkName_vfork;
62   CheckName checkName_FloatLoopCounter;
63   CheckName checkName_UncheckedReturn;
64 };
65 
66 class WalkAST : public StmtVisitor<WalkAST> {
67   BugReporter &BR;
68   AnalysisDeclContext* AC;
69   enum { num_setids = 6 };
70   IdentifierInfo *II_setid[num_setids];
71 
72   const bool CheckRand;
73   const ChecksFilter &filter;
74 
75 public:
76   WalkAST(BugReporter &br, AnalysisDeclContext* ac,
77           const ChecksFilter &f)
78   : BR(br), AC(ac), II_setid(),
79     CheckRand(isArc4RandomAvailable(BR.getContext())),
80     filter(f) {}
81 
82   // Statement visitor methods.
83   void VisitCallExpr(CallExpr *CE);
84   void VisitForStmt(ForStmt *S);
85   void VisitCompoundStmt (CompoundStmt *S);
86   void VisitStmt(Stmt *S) { VisitChildren(S); }
87 
88   void VisitChildren(Stmt *S);
89 
90   // Helpers.
91   bool checkCall_strCommon(const CallExpr *CE, const FunctionDecl *FD);
92 
93   typedef void (WalkAST::*FnCheck)(const CallExpr *, const FunctionDecl *);
94 
95   // Checker-specific methods.
96   void checkLoopConditionForFloat(const ForStmt *FS);
97   void checkCall_bcmp(const CallExpr *CE, const FunctionDecl *FD);
98   void checkCall_bcopy(const CallExpr *CE, const FunctionDecl *FD);
99   void checkCall_bzero(const CallExpr *CE, const FunctionDecl *FD);
100   void checkCall_gets(const CallExpr *CE, const FunctionDecl *FD);
101   void checkCall_getpw(const CallExpr *CE, const FunctionDecl *FD);
102   void checkCall_mktemp(const CallExpr *CE, const FunctionDecl *FD);
103   void checkCall_mkstemp(const CallExpr *CE, const FunctionDecl *FD);
104   void checkCall_strcpy(const CallExpr *CE, const FunctionDecl *FD);
105   void checkCall_strcat(const CallExpr *CE, const FunctionDecl *FD);
106   void checkCall_rand(const CallExpr *CE, const FunctionDecl *FD);
107   void checkCall_random(const CallExpr *CE, const FunctionDecl *FD);
108   void checkCall_vfork(const CallExpr *CE, const FunctionDecl *FD);
109   void checkUncheckedReturnValue(CallExpr *CE);
110 };
111 } // end anonymous namespace
112 
113 //===----------------------------------------------------------------------===//
114 // AST walking.
115 //===----------------------------------------------------------------------===//
116 
117 void WalkAST::VisitChildren(Stmt *S) {
118   for (Stmt *Child : S->children())
119     if (Child)
120       Visit(Child);
121 }
122 
123 void WalkAST::VisitCallExpr(CallExpr *CE) {
124   // Get the callee.
125   const FunctionDecl *FD = CE->getDirectCallee();
126 
127   if (!FD)
128     return;
129 
130   // Get the name of the callee. If it's a builtin, strip off the prefix.
131   IdentifierInfo *II = FD->getIdentifier();
132   if (!II)   // if no identifier, not a simple C function
133     return;
134   StringRef Name = II->getName();
135   if (Name.startswith("__builtin_"))
136     Name = Name.substr(10);
137 
138   // Set the evaluation function by switching on the callee name.
139   FnCheck evalFunction = llvm::StringSwitch<FnCheck>(Name)
140     .Case("bcmp", &WalkAST::checkCall_bcmp)
141     .Case("bcopy", &WalkAST::checkCall_bcopy)
142     .Case("bzero", &WalkAST::checkCall_bzero)
143     .Case("gets", &WalkAST::checkCall_gets)
144     .Case("getpw", &WalkAST::checkCall_getpw)
145     .Case("mktemp", &WalkAST::checkCall_mktemp)
146     .Case("mkstemp", &WalkAST::checkCall_mkstemp)
147     .Case("mkdtemp", &WalkAST::checkCall_mkstemp)
148     .Case("mkstemps", &WalkAST::checkCall_mkstemp)
149     .Cases("strcpy", "__strcpy_chk", &WalkAST::checkCall_strcpy)
150     .Cases("strcat", "__strcat_chk", &WalkAST::checkCall_strcat)
151     .Case("drand48", &WalkAST::checkCall_rand)
152     .Case("erand48", &WalkAST::checkCall_rand)
153     .Case("jrand48", &WalkAST::checkCall_rand)
154     .Case("lrand48", &WalkAST::checkCall_rand)
155     .Case("mrand48", &WalkAST::checkCall_rand)
156     .Case("nrand48", &WalkAST::checkCall_rand)
157     .Case("lcong48", &WalkAST::checkCall_rand)
158     .Case("rand", &WalkAST::checkCall_rand)
159     .Case("rand_r", &WalkAST::checkCall_rand)
160     .Case("random", &WalkAST::checkCall_random)
161     .Case("vfork", &WalkAST::checkCall_vfork)
162     .Default(nullptr);
163 
164   // If the callee isn't defined, it is not of security concern.
165   // Check and evaluate the call.
166   if (evalFunction)
167     (this->*evalFunction)(CE, FD);
168 
169   // Recurse and check children.
170   VisitChildren(CE);
171 }
172 
173 void WalkAST::VisitCompoundStmt(CompoundStmt *S) {
174   for (Stmt *Child : S->children())
175     if (Child) {
176       if (CallExpr *CE = dyn_cast<CallExpr>(Child))
177         checkUncheckedReturnValue(CE);
178       Visit(Child);
179     }
180 }
181 
182 void WalkAST::VisitForStmt(ForStmt *FS) {
183   checkLoopConditionForFloat(FS);
184 
185   // Recurse and check children.
186   VisitChildren(FS);
187 }
188 
189 //===----------------------------------------------------------------------===//
190 // Check: floating point variable used as loop counter.
191 // Originally: <rdar://problem/6336718>
192 // Implements: CERT security coding advisory FLP-30.
193 //===----------------------------------------------------------------------===//
194 
195 static const DeclRefExpr*
196 getIncrementedVar(const Expr *expr, const VarDecl *x, const VarDecl *y) {
197   expr = expr->IgnoreParenCasts();
198 
199   if (const BinaryOperator *B = dyn_cast<BinaryOperator>(expr)) {
200     if (!(B->isAssignmentOp() || B->isCompoundAssignmentOp() ||
201           B->getOpcode() == BO_Comma))
202       return nullptr;
203 
204     if (const DeclRefExpr *lhs = getIncrementedVar(B->getLHS(), x, y))
205       return lhs;
206 
207     if (const DeclRefExpr *rhs = getIncrementedVar(B->getRHS(), x, y))
208       return rhs;
209 
210     return nullptr;
211   }
212 
213   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(expr)) {
214     const NamedDecl *ND = DR->getDecl();
215     return ND == x || ND == y ? DR : nullptr;
216   }
217 
218   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(expr))
219     return U->isIncrementDecrementOp()
220       ? getIncrementedVar(U->getSubExpr(), x, y) : nullptr;
221 
222   return nullptr;
223 }
224 
225 /// CheckLoopConditionForFloat - This check looks for 'for' statements that
226 ///  use a floating point variable as a loop counter.
227 ///  CERT: FLP30-C, FLP30-CPP.
228 ///
229 void WalkAST::checkLoopConditionForFloat(const ForStmt *FS) {
230   if (!filter.check_FloatLoopCounter)
231     return;
232 
233   // Does the loop have a condition?
234   const Expr *condition = FS->getCond();
235 
236   if (!condition)
237     return;
238 
239   // Does the loop have an increment?
240   const Expr *increment = FS->getInc();
241 
242   if (!increment)
243     return;
244 
245   // Strip away '()' and casts.
246   condition = condition->IgnoreParenCasts();
247   increment = increment->IgnoreParenCasts();
248 
249   // Is the loop condition a comparison?
250   const BinaryOperator *B = dyn_cast<BinaryOperator>(condition);
251 
252   if (!B)
253     return;
254 
255   // Is this a comparison?
256   if (!(B->isRelationalOp() || B->isEqualityOp()))
257     return;
258 
259   // Are we comparing variables?
260   const DeclRefExpr *drLHS =
261     dyn_cast<DeclRefExpr>(B->getLHS()->IgnoreParenLValueCasts());
262   const DeclRefExpr *drRHS =
263     dyn_cast<DeclRefExpr>(B->getRHS()->IgnoreParenLValueCasts());
264 
265   // Does at least one of the variables have a floating point type?
266   drLHS = drLHS && drLHS->getType()->isRealFloatingType() ? drLHS : nullptr;
267   drRHS = drRHS && drRHS->getType()->isRealFloatingType() ? drRHS : nullptr;
268 
269   if (!drLHS && !drRHS)
270     return;
271 
272   const VarDecl *vdLHS = drLHS ? dyn_cast<VarDecl>(drLHS->getDecl()) : nullptr;
273   const VarDecl *vdRHS = drRHS ? dyn_cast<VarDecl>(drRHS->getDecl()) : nullptr;
274 
275   if (!vdLHS && !vdRHS)
276     return;
277 
278   // Does either variable appear in increment?
279   const DeclRefExpr *drInc = getIncrementedVar(increment, vdLHS, vdRHS);
280 
281   if (!drInc)
282     return;
283 
284   // Emit the error.  First figure out which DeclRefExpr in the condition
285   // referenced the compared variable.
286   assert(drInc->getDecl());
287   const DeclRefExpr *drCond = vdLHS == drInc->getDecl() ? drLHS : drRHS;
288 
289   SmallVector<SourceRange, 2> ranges;
290   SmallString<256> sbuf;
291   llvm::raw_svector_ostream os(sbuf);
292 
293   os << "Variable '" << drCond->getDecl()->getName()
294      << "' with floating point type '" << drCond->getType().getAsString()
295      << "' should not be used as a loop counter";
296 
297   ranges.push_back(drCond->getSourceRange());
298   ranges.push_back(drInc->getSourceRange());
299 
300   const char *bugType = "Floating point variable used as loop counter";
301 
302   PathDiagnosticLocation FSLoc =
303     PathDiagnosticLocation::createBegin(FS, BR.getSourceManager(), AC);
304   BR.EmitBasicReport(AC->getDecl(), filter.checkName_FloatLoopCounter,
305                      bugType, "Security", os.str(),
306                      FSLoc, ranges);
307 }
308 
309 //===----------------------------------------------------------------------===//
310 // Check: Any use of bcmp.
311 // CWE-477: Use of Obsolete Functions
312 // bcmp was deprecated in POSIX.1-2008
313 //===----------------------------------------------------------------------===//
314 
315 void WalkAST::checkCall_bcmp(const CallExpr *CE, const FunctionDecl *FD) {
316   if (!filter.check_bcmp)
317     return;
318 
319   const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>();
320   if (!FPT)
321     return;
322 
323   // Verify that the function takes three arguments.
324   if (FPT->getNumParams() != 3)
325     return;
326 
327   for (int i = 0; i < 2; i++) {
328     // Verify the first and second argument type is void*.
329     const PointerType *PT = FPT->getParamType(i)->getAs<PointerType>();
330     if (!PT)
331       return;
332 
333     if (PT->getPointeeType().getUnqualifiedType() != BR.getContext().VoidTy)
334       return;
335   }
336 
337   // Verify the third argument type is integer.
338   if (!FPT->getParamType(2)->isIntegralOrUnscopedEnumerationType())
339     return;
340 
341   // Issue a warning.
342   PathDiagnosticLocation CELoc =
343     PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
344   BR.EmitBasicReport(AC->getDecl(), filter.checkName_bcmp,
345                      "Use of deprecated function in call to 'bcmp()'",
346                      "Security",
347                      "The bcmp() function is obsoleted by memcmp().",
348                      CELoc, CE->getCallee()->getSourceRange());
349 }
350 
351 //===----------------------------------------------------------------------===//
352 // Check: Any use of bcopy.
353 // CWE-477: Use of Obsolete Functions
354 // bcopy was deprecated in POSIX.1-2008
355 //===----------------------------------------------------------------------===//
356 
357 void WalkAST::checkCall_bcopy(const CallExpr *CE, const FunctionDecl *FD) {
358   if (!filter.check_bcopy)
359     return;
360 
361   const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>();
362   if (!FPT)
363     return;
364 
365   // Verify that the function takes three arguments.
366   if (FPT->getNumParams() != 3)
367     return;
368 
369   for (int i = 0; i < 2; i++) {
370     // Verify the first and second argument type is void*.
371     const PointerType *PT = FPT->getParamType(i)->getAs<PointerType>();
372     if (!PT)
373       return;
374 
375     if (PT->getPointeeType().getUnqualifiedType() != BR.getContext().VoidTy)
376       return;
377   }
378 
379   // Verify the third argument type is integer.
380   if (!FPT->getParamType(2)->isIntegralOrUnscopedEnumerationType())
381     return;
382 
383   // Issue a warning.
384   PathDiagnosticLocation CELoc =
385     PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
386   BR.EmitBasicReport(AC->getDecl(), filter.checkName_bcopy,
387                      "Use of deprecated function in call to 'bcopy()'",
388                      "Security",
389                      "The bcopy() function is obsoleted by memcpy() "
390                      "or memmove().",
391                      CELoc, CE->getCallee()->getSourceRange());
392 }
393 
394 //===----------------------------------------------------------------------===//
395 // Check: Any use of bzero.
396 // CWE-477: Use of Obsolete Functions
397 // bzero was deprecated in POSIX.1-2008
398 //===----------------------------------------------------------------------===//
399 
400 void WalkAST::checkCall_bzero(const CallExpr *CE, const FunctionDecl *FD) {
401   if (!filter.check_bzero)
402     return;
403 
404   const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>();
405   if (!FPT)
406     return;
407 
408   // Verify that the function takes two arguments.
409   if (FPT->getNumParams() != 2)
410     return;
411 
412   // Verify the first argument type is void*.
413   const PointerType *PT = FPT->getParamType(0)->getAs<PointerType>();
414   if (!PT)
415     return;
416 
417   if (PT->getPointeeType().getUnqualifiedType() != BR.getContext().VoidTy)
418     return;
419 
420   // Verify the second argument type is integer.
421   if (!FPT->getParamType(1)->isIntegralOrUnscopedEnumerationType())
422     return;
423 
424   // Issue a warning.
425   PathDiagnosticLocation CELoc =
426     PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
427   BR.EmitBasicReport(AC->getDecl(), filter.checkName_bzero,
428                      "Use of deprecated function in call to 'bzero()'",
429                      "Security",
430                      "The bzero() function is obsoleted by memset().",
431                      CELoc, CE->getCallee()->getSourceRange());
432 }
433 
434 
435 //===----------------------------------------------------------------------===//
436 // Check: Any use of 'gets' is insecure.
437 // Originally: <rdar://problem/6335715>
438 // Implements (part of): 300-BSI (buildsecurityin.us-cert.gov)
439 // CWE-242: Use of Inherently Dangerous Function
440 //===----------------------------------------------------------------------===//
441 
442 void WalkAST::checkCall_gets(const CallExpr *CE, const FunctionDecl *FD) {
443   if (!filter.check_gets)
444     return;
445 
446   const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>();
447   if (!FPT)
448     return;
449 
450   // Verify that the function takes a single argument.
451   if (FPT->getNumParams() != 1)
452     return;
453 
454   // Is the argument a 'char*'?
455   const PointerType *PT = FPT->getParamType(0)->getAs<PointerType>();
456   if (!PT)
457     return;
458 
459   if (PT->getPointeeType().getUnqualifiedType() != BR.getContext().CharTy)
460     return;
461 
462   // Issue a warning.
463   PathDiagnosticLocation CELoc =
464     PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
465   BR.EmitBasicReport(AC->getDecl(), filter.checkName_gets,
466                      "Potential buffer overflow in call to 'gets'",
467                      "Security",
468                      "Call to function 'gets' is extremely insecure as it can "
469                      "always result in a buffer overflow",
470                      CELoc, CE->getCallee()->getSourceRange());
471 }
472 
473 //===----------------------------------------------------------------------===//
474 // Check: Any use of 'getpwd' is insecure.
475 // CWE-477: Use of Obsolete Functions
476 //===----------------------------------------------------------------------===//
477 
478 void WalkAST::checkCall_getpw(const CallExpr *CE, const FunctionDecl *FD) {
479   if (!filter.check_getpw)
480     return;
481 
482   const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>();
483   if (!FPT)
484     return;
485 
486   // Verify that the function takes two arguments.
487   if (FPT->getNumParams() != 2)
488     return;
489 
490   // Verify the first argument type is integer.
491   if (!FPT->getParamType(0)->isIntegralOrUnscopedEnumerationType())
492     return;
493 
494   // Verify the second argument type is char*.
495   const PointerType *PT = FPT->getParamType(1)->getAs<PointerType>();
496   if (!PT)
497     return;
498 
499   if (PT->getPointeeType().getUnqualifiedType() != BR.getContext().CharTy)
500     return;
501 
502   // Issue a warning.
503   PathDiagnosticLocation CELoc =
504     PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
505   BR.EmitBasicReport(AC->getDecl(), filter.checkName_getpw,
506                      "Potential buffer overflow in call to 'getpw'",
507                      "Security",
508                      "The getpw() function is dangerous as it may overflow the "
509                      "provided buffer. It is obsoleted by getpwuid().",
510                      CELoc, CE->getCallee()->getSourceRange());
511 }
512 
513 //===----------------------------------------------------------------------===//
514 // Check: Any use of 'mktemp' is insecure.  It is obsoleted by mkstemp().
515 // CWE-377: Insecure Temporary File
516 //===----------------------------------------------------------------------===//
517 
518 void WalkAST::checkCall_mktemp(const CallExpr *CE, const FunctionDecl *FD) {
519   if (!filter.check_mktemp) {
520     // Fall back to the security check of looking for enough 'X's in the
521     // format string, since that is a less severe warning.
522     checkCall_mkstemp(CE, FD);
523     return;
524   }
525 
526   const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>();
527   if(!FPT)
528     return;
529 
530   // Verify that the function takes a single argument.
531   if (FPT->getNumParams() != 1)
532     return;
533 
534   // Verify that the argument is Pointer Type.
535   const PointerType *PT = FPT->getParamType(0)->getAs<PointerType>();
536   if (!PT)
537     return;
538 
539   // Verify that the argument is a 'char*'.
540   if (PT->getPointeeType().getUnqualifiedType() != BR.getContext().CharTy)
541     return;
542 
543   // Issue a warning.
544   PathDiagnosticLocation CELoc =
545     PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
546   BR.EmitBasicReport(AC->getDecl(), filter.checkName_mktemp,
547                      "Potential insecure temporary file in call 'mktemp'",
548                      "Security",
549                      "Call to function 'mktemp' is insecure as it always "
550                      "creates or uses insecure temporary file.  Use 'mkstemp' "
551                      "instead",
552                      CELoc, CE->getCallee()->getSourceRange());
553 }
554 
555 
556 //===----------------------------------------------------------------------===//
557 // Check: Use of 'mkstemp', 'mktemp', 'mkdtemp' should contain at least 6 X's.
558 //===----------------------------------------------------------------------===//
559 
560 void WalkAST::checkCall_mkstemp(const CallExpr *CE, const FunctionDecl *FD) {
561   if (!filter.check_mkstemp)
562     return;
563 
564   StringRef Name = FD->getIdentifier()->getName();
565   std::pair<signed, signed> ArgSuffix =
566     llvm::StringSwitch<std::pair<signed, signed> >(Name)
567       .Case("mktemp", std::make_pair(0,-1))
568       .Case("mkstemp", std::make_pair(0,-1))
569       .Case("mkdtemp", std::make_pair(0,-1))
570       .Case("mkstemps", std::make_pair(0,1))
571       .Default(std::make_pair(-1, -1));
572 
573   assert(ArgSuffix.first >= 0 && "Unsupported function");
574 
575   // Check if the number of arguments is consistent with out expectations.
576   unsigned numArgs = CE->getNumArgs();
577   if ((signed) numArgs <= ArgSuffix.first)
578     return;
579 
580   const StringLiteral *strArg =
581     dyn_cast<StringLiteral>(CE->getArg((unsigned)ArgSuffix.first)
582                               ->IgnoreParenImpCasts());
583 
584   // Currently we only handle string literals.  It is possible to do better,
585   // either by looking at references to const variables, or by doing real
586   // flow analysis.
587   if (!strArg || strArg->getCharByteWidth() != 1)
588     return;
589 
590   // Count the number of X's, taking into account a possible cutoff suffix.
591   StringRef str = strArg->getString();
592   unsigned numX = 0;
593   unsigned n = str.size();
594 
595   // Take into account the suffix.
596   unsigned suffix = 0;
597   if (ArgSuffix.second >= 0) {
598     const Expr *suffixEx = CE->getArg((unsigned)ArgSuffix.second);
599     Expr::EvalResult EVResult;
600     if (!suffixEx->EvaluateAsInt(EVResult, BR.getContext()))
601       return;
602     llvm::APSInt Result = EVResult.Val.getInt();
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 
654   if (const auto *Array = dyn_cast<ConstantArrayType>(Target->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 
752     if (! PT->getPointeeType()->isIntegralOrUnscopedEnumerationType())
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++)
870     if (!FTP->getParamType(i)->isIntegralOrUnscopedEnumerationType())
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 void ento::registerSecuritySyntaxChecker(CheckerManager &mgr) {
909   mgr.registerChecker<SecuritySyntaxChecker>();
910 }
911 
912 bool ento::shouldRegisterSecuritySyntaxChecker(const LangOptions &LO) {
913   return true;
914 }
915 
916 #define REGISTER_CHECKER(name)                                                 \
917   void ento::register##name(CheckerManager &mgr) {                             \
918     SecuritySyntaxChecker *checker =                                           \
919         mgr.registerChecker<SecuritySyntaxChecker>();                          \
920     checker->filter.check_##name = true;                                       \
921     checker->filter.checkName_##name = mgr.getCurrentCheckName();              \
922   }                                                                            \
923                                                                                \
924   bool ento::shouldRegister##name(const LangOptions &LO) {                     \
925     return true;                                                               \
926   }
927 
928 REGISTER_CHECKER(bcmp)
929 REGISTER_CHECKER(bcopy)
930 REGISTER_CHECKER(bzero)
931 REGISTER_CHECKER(gets)
932 REGISTER_CHECKER(getpw)
933 REGISTER_CHECKER(mkstemp)
934 REGISTER_CHECKER(mktemp)
935 REGISTER_CHECKER(strcpy)
936 REGISTER_CHECKER(rand)
937 REGISTER_CHECKER(vfork)
938 REGISTER_CHECKER(FloatLoopCounter)
939 REGISTER_CHECKER(UncheckedReturn)
940 
941 
942