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