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