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