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