xref: /llvm-project/clang/lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp (revision c29bed398971e550a4cacddf3dcf2b6b8a6e37b4)
1 //==- CheckSecuritySyntaxOnly.cpp - Basic security checks --------*- C++ -*-==//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file defines a set of flow-insensitive security checks.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "ClangSACheckers.h"
15 #include "clang/Analysis/AnalysisContext.h"
16 #include "clang/AST/StmtVisitor.h"
17 #include "clang/Basic/TargetInfo.h"
18 #include "clang/StaticAnalyzer/Core/Checker.h"
19 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
20 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.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::FreeBSD ||
31          T.getOS() == llvm::Triple::NetBSD ||
32          T.getOS() == llvm::Triple::OpenBSD ||
33          T.getOS() == llvm::Triple::DragonFly;
34 }
35 
36 namespace {
37 class WalkAST : public StmtVisitor<WalkAST> {
38   BugReporter &BR;
39   AnalysisContext* AC;
40   enum { num_setids = 6 };
41   IdentifierInfo *II_setid[num_setids];
42 
43   const bool CheckRand;
44 
45 public:
46   WalkAST(BugReporter &br, AnalysisContext* ac)
47   : BR(br), AC(ac), II_setid(),
48     CheckRand(isArc4RandomAvailable(BR.getContext())) {}
49 
50   // Statement visitor methods.
51   void VisitCallExpr(CallExpr *CE);
52   void VisitForStmt(ForStmt *S);
53   void VisitCompoundStmt (CompoundStmt *S);
54   void VisitStmt(Stmt *S) { VisitChildren(S); }
55 
56   void VisitChildren(Stmt *S);
57 
58   // Helpers.
59   bool checkCall_strCommon(const CallExpr *CE, const FunctionDecl *FD);
60 
61   typedef void (WalkAST::*FnCheck)(const CallExpr *,
62 				   const FunctionDecl *);
63 
64   // Checker-specific methods.
65   void checkLoopConditionForFloat(const ForStmt *FS);
66   void checkCall_gets(const CallExpr *CE, const FunctionDecl *FD);
67   void checkCall_getpw(const CallExpr *CE, const FunctionDecl *FD);
68   void checkCall_mktemp(const CallExpr *CE, const FunctionDecl *FD);
69   void checkCall_strcpy(const CallExpr *CE, const FunctionDecl *FD);
70   void checkCall_strcat(const CallExpr *CE, const FunctionDecl *FD);
71   void checkCall_rand(const CallExpr *CE, const FunctionDecl *FD);
72   void checkCall_random(const CallExpr *CE, const FunctionDecl *FD);
73   void checkUncheckedReturnValue(CallExpr *CE);
74 };
75 } // end anonymous namespace
76 
77 //===----------------------------------------------------------------------===//
78 // AST walking.
79 //===----------------------------------------------------------------------===//
80 
81 void WalkAST::VisitChildren(Stmt *S) {
82   for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
83     if (Stmt *child = *I)
84       Visit(child);
85 }
86 
87 void WalkAST::VisitCallExpr(CallExpr *CE) {
88   // Get the callee.
89   const FunctionDecl *FD = CE->getDirectCallee();
90 
91   if (!FD)
92     return;
93 
94   // Get the name of the callee. If it's a builtin, strip off the prefix.
95   IdentifierInfo *II = FD->getIdentifier();
96   if (!II)   // if no identifier, not a simple C function
97     return;
98   StringRef Name = II->getName();
99   if (Name.startswith("__builtin_"))
100     Name = Name.substr(10);
101 
102   // Set the evaluation function by switching on the callee name.
103   FnCheck evalFunction = llvm::StringSwitch<FnCheck>(Name)
104     .Case("gets", &WalkAST::checkCall_gets)
105     .Case("getpw", &WalkAST::checkCall_getpw)
106     .Case("mktemp", &WalkAST::checkCall_mktemp)
107     .Cases("strcpy", "__strcpy_chk", &WalkAST::checkCall_strcpy)
108     .Cases("strcat", "__strcat_chk", &WalkAST::checkCall_strcat)
109     .Case("drand48", &WalkAST::checkCall_rand)
110     .Case("erand48", &WalkAST::checkCall_rand)
111     .Case("jrand48", &WalkAST::checkCall_rand)
112     .Case("lrand48", &WalkAST::checkCall_rand)
113     .Case("mrand48", &WalkAST::checkCall_rand)
114     .Case("nrand48", &WalkAST::checkCall_rand)
115     .Case("lcong48", &WalkAST::checkCall_rand)
116     .Case("rand", &WalkAST::checkCall_rand)
117     .Case("rand_r", &WalkAST::checkCall_rand)
118     .Case("random", &WalkAST::checkCall_random)
119     .Default(NULL);
120 
121   // If the callee isn't defined, it is not of security concern.
122   // Check and evaluate the call.
123   if (evalFunction)
124     (this->*evalFunction)(CE, FD);
125 
126   // Recurse and check children.
127   VisitChildren(CE);
128 }
129 
130 void WalkAST::VisitCompoundStmt(CompoundStmt *S) {
131   for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
132     if (Stmt *child = *I) {
133       if (CallExpr *CE = dyn_cast<CallExpr>(child))
134         checkUncheckedReturnValue(CE);
135       Visit(child);
136     }
137 }
138 
139 void WalkAST::VisitForStmt(ForStmt *FS) {
140   checkLoopConditionForFloat(FS);
141 
142   // Recurse and check children.
143   VisitChildren(FS);
144 }
145 
146 //===----------------------------------------------------------------------===//
147 // Check: floating poing variable used as loop counter.
148 // Originally: <rdar://problem/6336718>
149 // Implements: CERT security coding advisory FLP-30.
150 //===----------------------------------------------------------------------===//
151 
152 static const DeclRefExpr*
153 getIncrementedVar(const Expr *expr, const VarDecl *x, const VarDecl *y) {
154   expr = expr->IgnoreParenCasts();
155 
156   if (const BinaryOperator *B = dyn_cast<BinaryOperator>(expr)) {
157     if (!(B->isAssignmentOp() || B->isCompoundAssignmentOp() ||
158           B->getOpcode() == BO_Comma))
159       return NULL;
160 
161     if (const DeclRefExpr *lhs = getIncrementedVar(B->getLHS(), x, y))
162       return lhs;
163 
164     if (const DeclRefExpr *rhs = getIncrementedVar(B->getRHS(), x, y))
165       return rhs;
166 
167     return NULL;
168   }
169 
170   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(expr)) {
171     const NamedDecl *ND = DR->getDecl();
172     return ND == x || ND == y ? DR : NULL;
173   }
174 
175   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(expr))
176     return U->isIncrementDecrementOp()
177       ? getIncrementedVar(U->getSubExpr(), x, y) : NULL;
178 
179   return NULL;
180 }
181 
182 /// CheckLoopConditionForFloat - This check looks for 'for' statements that
183 ///  use a floating point variable as a loop counter.
184 ///  CERT: FLP30-C, FLP30-CPP.
185 ///
186 void WalkAST::checkLoopConditionForFloat(const ForStmt *FS) {
187   // Does the loop have a condition?
188   const Expr *condition = FS->getCond();
189 
190   if (!condition)
191     return;
192 
193   // Does the loop have an increment?
194   const Expr *increment = FS->getInc();
195 
196   if (!increment)
197     return;
198 
199   // Strip away '()' and casts.
200   condition = condition->IgnoreParenCasts();
201   increment = increment->IgnoreParenCasts();
202 
203   // Is the loop condition a comparison?
204   const BinaryOperator *B = dyn_cast<BinaryOperator>(condition);
205 
206   if (!B)
207     return;
208 
209   // Is this a comparison?
210   if (!(B->isRelationalOp() || B->isEqualityOp()))
211     return;
212 
213   // Are we comparing variables?
214   const DeclRefExpr *drLHS =
215     dyn_cast<DeclRefExpr>(B->getLHS()->IgnoreParenLValueCasts());
216   const DeclRefExpr *drRHS =
217     dyn_cast<DeclRefExpr>(B->getRHS()->IgnoreParenLValueCasts());
218 
219   // Does at least one of the variables have a floating point type?
220   drLHS = drLHS && drLHS->getType()->isRealFloatingType() ? drLHS : NULL;
221   drRHS = drRHS && drRHS->getType()->isRealFloatingType() ? drRHS : NULL;
222 
223   if (!drLHS && !drRHS)
224     return;
225 
226   const VarDecl *vdLHS = drLHS ? dyn_cast<VarDecl>(drLHS->getDecl()) : NULL;
227   const VarDecl *vdRHS = drRHS ? dyn_cast<VarDecl>(drRHS->getDecl()) : NULL;
228 
229   if (!vdLHS && !vdRHS)
230     return;
231 
232   // Does either variable appear in increment?
233   const DeclRefExpr *drInc = getIncrementedVar(increment, vdLHS, vdRHS);
234 
235   if (!drInc)
236     return;
237 
238   // Emit the error.  First figure out which DeclRefExpr in the condition
239   // referenced the compared variable.
240   const DeclRefExpr *drCond = vdLHS == drInc->getDecl() ? drLHS : drRHS;
241 
242   SmallVector<SourceRange, 2> ranges;
243   llvm::SmallString<256> sbuf;
244   llvm::raw_svector_ostream os(sbuf);
245 
246   os << "Variable '" << drCond->getDecl()->getName()
247      << "' with floating point type '" << drCond->getType().getAsString()
248      << "' should not be used as a loop counter";
249 
250   ranges.push_back(drCond->getSourceRange());
251   ranges.push_back(drInc->getSourceRange());
252 
253   const char *bugType = "Floating point variable used as loop counter";
254 
255   PathDiagnosticLocation FSLoc =
256     PathDiagnosticLocation::createBegin(FS, BR.getSourceManager(), AC);
257   BR.EmitBasicReport(bugType, "Security", os.str(),
258                      FSLoc, ranges.data(), ranges.size());
259 }
260 
261 //===----------------------------------------------------------------------===//
262 // Check: Any use of 'gets' is insecure.
263 // Originally: <rdar://problem/6335715>
264 // Implements (part of): 300-BSI (buildsecurityin.us-cert.gov)
265 // CWE-242: Use of Inherently Dangerous Function
266 //===----------------------------------------------------------------------===//
267 
268 void WalkAST::checkCall_gets(const CallExpr *CE, const FunctionDecl *FD) {
269   const FunctionProtoType *FPT
270     = dyn_cast<FunctionProtoType>(FD->getType().IgnoreParens());
271   if (!FPT)
272     return;
273 
274   // Verify that the function takes a single argument.
275   if (FPT->getNumArgs() != 1)
276     return;
277 
278   // Is the argument a 'char*'?
279   const PointerType *PT = dyn_cast<PointerType>(FPT->getArgType(0));
280   if (!PT)
281     return;
282 
283   if (PT->getPointeeType().getUnqualifiedType() != BR.getContext().CharTy)
284     return;
285 
286   // Issue a warning.
287   SourceRange R = CE->getCallee()->getSourceRange();
288   PathDiagnosticLocation CELoc =
289     PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
290   BR.EmitBasicReport("Potential buffer overflow in call to 'gets'",
291                      "Security",
292                      "Call to function 'gets' is extremely insecure as it can "
293                      "always result in a buffer overflow",
294                      CELoc, &R, 1);
295 }
296 
297 //===----------------------------------------------------------------------===//
298 // Check: Any use of 'getpwd' is insecure.
299 // CWE-477: Use of Obsolete Functions
300 //===----------------------------------------------------------------------===//
301 
302 void WalkAST::checkCall_getpw(const CallExpr *CE, const FunctionDecl *FD) {
303   const FunctionProtoType *FPT
304     = dyn_cast<FunctionProtoType>(FD->getType().IgnoreParens());
305   if (!FPT)
306     return;
307 
308   // Verify that the function takes two arguments.
309   if (FPT->getNumArgs() != 2)
310     return;
311 
312   // Verify the first argument type is integer.
313   if (!FPT->getArgType(0)->isIntegerType())
314     return;
315 
316   // Verify the second argument type is char*.
317   const PointerType *PT = dyn_cast<PointerType>(FPT->getArgType(1));
318   if (!PT)
319     return;
320 
321   if (PT->getPointeeType().getUnqualifiedType() != BR.getContext().CharTy)
322     return;
323 
324   // Issue a warning.
325   SourceRange R = CE->getCallee()->getSourceRange();
326   PathDiagnosticLocation CELoc =
327     PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
328   BR.EmitBasicReport("Potential buffer overflow in call to 'getpw'",
329                      "Security",
330                      "The getpw() function is dangerous as it may overflow the "
331                      "provided buffer. It is obsoleted by getpwuid().",
332                      CELoc, &R, 1);
333 }
334 
335 //===----------------------------------------------------------------------===//
336 // Check: Any use of 'mktemp' is insecure.It is obsoleted by mkstemp().
337 // CWE-377: Insecure Temporary File
338 //===----------------------------------------------------------------------===//
339 
340 void WalkAST::checkCall_mktemp(const CallExpr *CE, const FunctionDecl *FD) {
341   const FunctionProtoType *FPT
342     = dyn_cast<FunctionProtoType>(FD->getType().IgnoreParens());
343   if(!FPT)
344     return;
345 
346   // Verify that the function takes a single argument.
347   if (FPT->getNumArgs() != 1)
348     return;
349 
350   // Verify that the argument is Pointer Type.
351   const PointerType *PT = dyn_cast<PointerType>(FPT->getArgType(0));
352   if (!PT)
353     return;
354 
355   // Verify that the argument is a 'char*'.
356   if (PT->getPointeeType().getUnqualifiedType() != BR.getContext().CharTy)
357     return;
358 
359   // Issue a waring.
360   SourceRange R = CE->getCallee()->getSourceRange();
361   PathDiagnosticLocation CELoc =
362     PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
363   BR.EmitBasicReport("Potential insecure temporary file in call 'mktemp'",
364                      "Security",
365                      "Call to function 'mktemp' is insecure as it always "
366                      "creates or uses insecure temporary file.  Use 'mkstemp' instead",
367                      CELoc, &R, 1);
368 }
369 
370 //===----------------------------------------------------------------------===//
371 // Check: Any use of 'strcpy' is insecure.
372 //
373 // CWE-119: Improper Restriction of Operations within
374 // the Bounds of a Memory Buffer
375 //===----------------------------------------------------------------------===//
376 void WalkAST::checkCall_strcpy(const CallExpr *CE, const FunctionDecl *FD) {
377   if (!checkCall_strCommon(CE, FD))
378     return;
379 
380   // Issue a warning.
381   SourceRange R = CE->getCallee()->getSourceRange();
382   PathDiagnosticLocation CELoc =
383     PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
384   BR.EmitBasicReport("Potential insecure memory buffer bounds restriction in "
385                      "call 'strcpy'",
386                      "Security",
387                      "Call to function 'strcpy' is insecure as it does not "
388 		     "provide bounding of the memory buffer. Replace "
389 		     "unbounded copy functions with analogous functions that "
390 		     "support length arguments such as 'strncpy'. CWE-119.",
391                      CELoc, &R, 1);
392 }
393 
394 //===----------------------------------------------------------------------===//
395 // Check: Any use of 'strcat' is insecure.
396 //
397 // CWE-119: Improper Restriction of Operations within
398 // the Bounds of a Memory Buffer
399 //===----------------------------------------------------------------------===//
400 void WalkAST::checkCall_strcat(const CallExpr *CE, const FunctionDecl *FD) {
401   if (!checkCall_strCommon(CE, FD))
402     return;
403 
404   // Issue a warning.
405   SourceRange R = CE->getCallee()->getSourceRange();
406   PathDiagnosticLocation CELoc =
407     PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
408   BR.EmitBasicReport("Potential insecure memory buffer bounds restriction in "
409 		     "call 'strcat'",
410 		     "Security",
411 		     "Call to function 'strcat' is insecure as it does not "
412 		     "provide bounding of the memory buffer. Replace "
413 		     "unbounded copy functions with analogous functions that "
414 		     "support length arguments such as 'strncat'. CWE-119.",
415                      CELoc, &R, 1);
416 }
417 
418 //===----------------------------------------------------------------------===//
419 // Common check for str* functions with no bounds parameters.
420 //===----------------------------------------------------------------------===//
421 bool WalkAST::checkCall_strCommon(const CallExpr *CE, const FunctionDecl *FD) {
422   const FunctionProtoType *FPT
423     = dyn_cast<FunctionProtoType>(FD->getType().IgnoreParens());
424   if (!FPT)
425     return false;
426 
427   // Verify the function takes two arguments, three in the _chk version.
428   int numArgs = FPT->getNumArgs();
429   if (numArgs != 2 && numArgs != 3)
430     return false;
431 
432   // Verify the type for both arguments.
433   for (int i = 0; i < 2; i++) {
434     // Verify that the arguments are pointers.
435     const PointerType *PT = dyn_cast<PointerType>(FPT->getArgType(i));
436     if (!PT)
437       return false;
438 
439     // Verify that the argument is a 'char*'.
440     if (PT->getPointeeType().getUnqualifiedType() != BR.getContext().CharTy)
441       return false;
442   }
443 
444   return true;
445 }
446 
447 //===----------------------------------------------------------------------===//
448 // Check: Linear congruent random number generators should not be used
449 // Originally: <rdar://problem/63371000>
450 // CWE-338: Use of cryptographically weak prng
451 //===----------------------------------------------------------------------===//
452 
453 void WalkAST::checkCall_rand(const CallExpr *CE, const FunctionDecl *FD) {
454   if (!CheckRand)
455     return;
456 
457   const FunctionProtoType *FTP
458     = dyn_cast<FunctionProtoType>(FD->getType().IgnoreParens());
459   if (!FTP)
460     return;
461 
462   if (FTP->getNumArgs() == 1) {
463     // Is the argument an 'unsigned short *'?
464     // (Actually any integer type is allowed.)
465     const PointerType *PT = dyn_cast<PointerType>(FTP->getArgType(0));
466     if (!PT)
467       return;
468 
469     if (! PT->getPointeeType()->isIntegerType())
470       return;
471   }
472   else if (FTP->getNumArgs() != 0)
473     return;
474 
475   // Issue a warning.
476   llvm::SmallString<256> buf1;
477   llvm::raw_svector_ostream os1(buf1);
478   os1 << '\'' << FD << "' is a poor random number generator";
479 
480   llvm::SmallString<256> buf2;
481   llvm::raw_svector_ostream os2(buf2);
482   os2 << "Function '" << FD
483       << "' is obsolete because it implements a poor random number generator."
484       << "  Use 'arc4random' instead";
485 
486   SourceRange R = CE->getCallee()->getSourceRange();
487   PathDiagnosticLocation CELoc =
488     PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
489   BR.EmitBasicReport(os1.str(), "Security", os2.str(), CELoc, &R, 1);
490 }
491 
492 //===----------------------------------------------------------------------===//
493 // Check: 'random' should not be used
494 // Originally: <rdar://problem/63371000>
495 //===----------------------------------------------------------------------===//
496 
497 void WalkAST::checkCall_random(const CallExpr *CE, const FunctionDecl *FD) {
498   if (!CheckRand)
499     return;
500 
501   const FunctionProtoType *FTP
502     = dyn_cast<FunctionProtoType>(FD->getType().IgnoreParens());
503   if (!FTP)
504     return;
505 
506   // Verify that the function takes no argument.
507   if (FTP->getNumArgs() != 0)
508     return;
509 
510   // Issue a warning.
511   SourceRange R = CE->getCallee()->getSourceRange();
512   PathDiagnosticLocation CELoc =
513     PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
514   BR.EmitBasicReport("'random' is not a secure random number generator",
515                      "Security",
516                      "The 'random' function produces a sequence of values that "
517                      "an adversary may be able to predict.  Use 'arc4random' "
518                      "instead", CELoc, &R, 1);
519 }
520 
521 //===----------------------------------------------------------------------===//
522 // Check: Should check whether privileges are dropped successfully.
523 // Originally: <rdar://problem/6337132>
524 //===----------------------------------------------------------------------===//
525 
526 void WalkAST::checkUncheckedReturnValue(CallExpr *CE) {
527   const FunctionDecl *FD = CE->getDirectCallee();
528   if (!FD)
529     return;
530 
531   if (II_setid[0] == NULL) {
532     static const char * const identifiers[num_setids] = {
533       "setuid", "setgid", "seteuid", "setegid",
534       "setreuid", "setregid"
535     };
536 
537     for (size_t i = 0; i < num_setids; i++)
538       II_setid[i] = &BR.getContext().Idents.get(identifiers[i]);
539   }
540 
541   const IdentifierInfo *id = FD->getIdentifier();
542   size_t identifierid;
543 
544   for (identifierid = 0; identifierid < num_setids; identifierid++)
545     if (id == II_setid[identifierid])
546       break;
547 
548   if (identifierid >= num_setids)
549     return;
550 
551   const FunctionProtoType *FTP
552     = dyn_cast<FunctionProtoType>(FD->getType().IgnoreParens());
553   if (!FTP)
554     return;
555 
556   // Verify that the function takes one or two arguments (depending on
557   //   the function).
558   if (FTP->getNumArgs() != (identifierid < 4 ? 1 : 2))
559     return;
560 
561   // The arguments must be integers.
562   for (unsigned i = 0; i < FTP->getNumArgs(); i++)
563     if (! FTP->getArgType(i)->isIntegerType())
564       return;
565 
566   // Issue a warning.
567   llvm::SmallString<256> buf1;
568   llvm::raw_svector_ostream os1(buf1);
569   os1 << "Return value is not checked in call to '" << FD << '\'';
570 
571   llvm::SmallString<256> buf2;
572   llvm::raw_svector_ostream os2(buf2);
573   os2 << "The return value from the call to '" << FD
574       << "' is not checked.  If an error occurs in '" << FD
575       << "', the following code may execute with unexpected privileges";
576 
577   SourceRange R = CE->getCallee()->getSourceRange();
578   PathDiagnosticLocation CELoc =
579     PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
580   BR.EmitBasicReport(os1.str(), "Security", os2.str(), CELoc, &R, 1);
581 }
582 
583 //===----------------------------------------------------------------------===//
584 // SecuritySyntaxChecker
585 //===----------------------------------------------------------------------===//
586 
587 namespace {
588 class SecuritySyntaxChecker : public Checker<check::ASTCodeBody> {
589 public:
590   void checkASTCodeBody(const Decl *D, AnalysisManager& mgr,
591                         BugReporter &BR) const {
592     WalkAST walker(BR, mgr.getAnalysisContext(D));
593     walker.Visit(D->getBody());
594   }
595 };
596 }
597 
598 void ento::registerSecuritySyntaxChecker(CheckerManager &mgr) {
599   mgr.registerChecker<SecuritySyntaxChecker>();
600 }
601