blob: 1bed9d1a5b87cc0ab0e60e36db6ffac51b9f0a65 [file] [log] [blame]
Ted Kremenekdbfb5f82009-07-23 01:07:19 +00001//==- 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/Analysis/PathSensitive/BugReporter.h"
15#include "clang/Analysis/LocalCheckers.h"
16#include "clang/AST/StmtVisitor.h"
17#include "llvm/Support/Compiler.h"
Ted Kremenek8baf86d2009-07-23 21:34:35 +000018#include "llvm/Support/raw_ostream.h"
Ted Kremenekdbfb5f82009-07-23 01:07:19 +000019
20using namespace clang;
21
22namespace {
23class VISIBILITY_HIDDEN WalkAST : public StmtVisitor<WalkAST> {
Ted Kremenekefcbb152009-07-23 22:29:41 +000024 BugReporter &BR;
Ted Kremenek65a81a92009-08-28 00:08:09 +000025 IdentifierInfo *II_gets;
Ted Kremenek24650472009-09-02 02:47:41 +000026 enum { num_rands = 9 };
27 IdentifierInfo *II_rand[num_rands];
28 IdentifierInfo *II_random;
29 enum { num_setids = 6 };
30 IdentifierInfo *II_setid[num_setids];
Ted Kremenek65a81a92009-08-28 00:08:09 +000031
Ted Kremenekdbfb5f82009-07-23 01:07:19 +000032public:
Ted Kremenekefcbb152009-07-23 22:29:41 +000033 WalkAST(BugReporter &br) : BR(br),
Ted Kremenek24650472009-09-02 02:47:41 +000034 II_gets(0), II_rand(), II_random(0), II_setid() {}
Ted Kremenekdbfb5f82009-07-23 01:07:19 +000035
36 // Statement visitor methods.
Ted Kremenekefcbb152009-07-23 22:29:41 +000037 void VisitCallExpr(CallExpr *CE);
Ted Kremenekdbfb5f82009-07-23 01:07:19 +000038 void VisitForStmt(ForStmt *S);
Ted Kremenek65a81a92009-08-28 00:08:09 +000039 void VisitCompoundStmt (CompoundStmt *S);
Ted Kremenek8baf86d2009-07-23 21:34:35 +000040 void VisitStmt(Stmt *S) { VisitChildren(S); }
Ted Kremenekdbfb5f82009-07-23 01:07:19 +000041
42 void VisitChildren(Stmt *S);
Ted Kremenekdbfb5f82009-07-23 01:07:19 +000043
Ted Kremenekefcbb152009-07-23 22:29:41 +000044 // Helpers.
45 IdentifierInfo *GetIdentifier(IdentifierInfo *& II, const char *str);
46
Ted Kremenekdbfb5f82009-07-23 01:07:19 +000047 // Checker-specific methods.
Ted Kremenek8baf86d2009-07-23 21:34:35 +000048 void CheckLoopConditionForFloat(const ForStmt *FS);
Ted Kremenekefcbb152009-07-23 22:29:41 +000049 void CheckCall_gets(const CallExpr *CE, const FunctionDecl *FD);
Ted Kremenek24650472009-09-02 02:47:41 +000050 void CheckCall_rand(const CallExpr *CE, const FunctionDecl *FD);
51 void CheckCall_random(const CallExpr *CE, const FunctionDecl *FD);
Ted Kremenek65a81a92009-08-28 00:08:09 +000052 void CheckUncheckedReturnValue(CallExpr *CE);
Ted Kremenekdbfb5f82009-07-23 01:07:19 +000053};
54} // end anonymous namespace
55
56//===----------------------------------------------------------------------===//
Ted Kremenekefcbb152009-07-23 22:29:41 +000057// Helper methods.
58//===----------------------------------------------------------------------===//
59
60IdentifierInfo *WalkAST::GetIdentifier(IdentifierInfo *& II, const char *str) {
61 if (!II)
62 II = &BR.getContext().Idents.get(str);
63
64 return II;
65}
66
67//===----------------------------------------------------------------------===//
Ted Kremenekdbfb5f82009-07-23 01:07:19 +000068// AST walking.
69//===----------------------------------------------------------------------===//
70
71void WalkAST::VisitChildren(Stmt *S) {
72 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
73 if (Stmt *child = *I)
74 Visit(child);
75}
76
Ted Kremenekefcbb152009-07-23 22:29:41 +000077void WalkAST::VisitCallExpr(CallExpr *CE) {
78 if (const FunctionDecl *FD = CE->getDirectCallee()) {
Ted Kremenek24650472009-09-02 02:47:41 +000079 CheckCall_gets(CE, FD);
80 CheckCall_rand(CE, FD);
81 CheckCall_random(CE, FD);
Ted Kremenekefcbb152009-07-23 22:29:41 +000082 }
83
84 // Recurse and check children.
85 VisitChildren(CE);
86}
87
Ted Kremenek65a81a92009-08-28 00:08:09 +000088void WalkAST::VisitCompoundStmt(CompoundStmt *S) {
89 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
90 if (Stmt *child = *I)
91 {
92 if (CallExpr *CE = dyn_cast<CallExpr>(child))
93 CheckUncheckedReturnValue(CE);
94 Visit(child);
95 }
96}
97
Ted Kremenek8baf86d2009-07-23 21:34:35 +000098void WalkAST::VisitForStmt(ForStmt *FS) {
99 CheckLoopConditionForFloat(FS);
Ted Kremenekdbfb5f82009-07-23 01:07:19 +0000100
Ted Kremenek8baf86d2009-07-23 21:34:35 +0000101 // Recurse and check children.
102 VisitChildren(FS);
Ted Kremenekdbfb5f82009-07-23 01:07:19 +0000103}
104
105//===----------------------------------------------------------------------===//
Ted Kremenek8baf86d2009-07-23 21:34:35 +0000106// Check: floating poing variable used as loop counter.
Ted Kremenek5abeb522009-07-23 21:44:18 +0000107// Originally: <rdar://problem/6336718>
108// Implements: CERT security coding advisory FLP-30.
Ted Kremenekdbfb5f82009-07-23 01:07:19 +0000109//===----------------------------------------------------------------------===//
110
Ted Kremenek8baf86d2009-07-23 21:34:35 +0000111static const DeclRefExpr*
112GetIncrementedVar(const Expr *expr, const VarDecl *x, const VarDecl *y) {
113 expr = expr->IgnoreParenCasts();
114
115 if (const BinaryOperator *B = dyn_cast<BinaryOperator>(expr)) {
116 if (!(B->isAssignmentOp() || B->isCompoundAssignmentOp() ||
117 B->getOpcode() == BinaryOperator::Comma))
118 return NULL;
119
120 if (const DeclRefExpr *lhs = GetIncrementedVar(B->getLHS(), x, y))
121 return lhs;
122
123 if (const DeclRefExpr *rhs = GetIncrementedVar(B->getRHS(), x, y))
124 return rhs;
125
126 return NULL;
Ted Kremenekdbfb5f82009-07-23 01:07:19 +0000127 }
Ted Kremenek8baf86d2009-07-23 21:34:35 +0000128
129 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(expr)) {
130 const NamedDecl *ND = DR->getDecl();
131 return ND == x || ND == y ? DR : NULL;
132 }
133
134 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(expr))
135 return U->isIncrementDecrementOp()
136 ? GetIncrementedVar(U->getSubExpr(), x, y) : NULL;
137
Ted Kremenekdbfb5f82009-07-23 01:07:19 +0000138 return NULL;
139}
140
Ted Kremenek8baf86d2009-07-23 21:34:35 +0000141/// CheckLoopConditionForFloat - This check looks for 'for' statements that
142/// use a floating point variable as a loop counter.
143/// CERT: FLP30-C, FLP30-CPP.
144///
145void WalkAST::CheckLoopConditionForFloat(const ForStmt *FS) {
146 // Does the loop have a condition?
147 const Expr *condition = FS->getCond();
148
149 if (!condition)
150 return;
151
152 // Does the loop have an increment?
153 const Expr *increment = FS->getInc();
154
155 if (!increment)
156 return;
157
158 // Strip away '()' and casts.
159 condition = condition->IgnoreParenCasts();
160 increment = increment->IgnoreParenCasts();
161
162 // Is the loop condition a comparison?
163 const BinaryOperator *B = dyn_cast<BinaryOperator>(condition);
164
165 if (!B)
166 return;
167
Ted Kremenekcad9f412009-07-24 20:26:31 +0000168 // Is this a comparison?
169 if (!(B->isRelationalOp() || B->isEqualityOp()))
Ted Kremenek8baf86d2009-07-23 21:34:35 +0000170 return;
Ted Kremenekcad9f412009-07-24 20:26:31 +0000171
Ted Kremenek8baf86d2009-07-23 21:34:35 +0000172 // Are we comparing variables?
173 const DeclRefExpr *drLHS = dyn_cast<DeclRefExpr>(B->getLHS()->IgnoreParens());
174 const DeclRefExpr *drRHS = dyn_cast<DeclRefExpr>(B->getRHS()->IgnoreParens());
175
Ted Kremenekcad9f412009-07-24 20:26:31 +0000176 // Does at least one of the variables have a floating point type?
177 drLHS = drLHS && drLHS->getType()->isFloatingType() ? drLHS : NULL;
178 drRHS = drRHS && drRHS->getType()->isFloatingType() ? drRHS : NULL;
179
Ted Kremenek8baf86d2009-07-23 21:34:35 +0000180 if (!drLHS && !drRHS)
181 return;
182
183 const VarDecl *vdLHS = drLHS ? dyn_cast<VarDecl>(drLHS->getDecl()) : NULL;
184 const VarDecl *vdRHS = drRHS ? dyn_cast<VarDecl>(drRHS->getDecl()) : NULL;
185
186 if (!vdLHS && !vdRHS)
187 return;
188
189 // Does either variable appear in increment?
190 const DeclRefExpr *drInc = GetIncrementedVar(increment, vdLHS, vdRHS);
191
192 if (!drInc)
193 return;
194
195 // Emit the error. First figure out which DeclRefExpr in the condition
196 // referenced the compared variable.
197 const DeclRefExpr *drCond = vdLHS == drInc->getDecl() ? drLHS : drRHS;
198
199 llvm::SmallVector<SourceRange, 2> ranges;
200 std::string sbuf;
201 llvm::raw_string_ostream os(sbuf);
202
203 os << "Variable '" << drCond->getDecl()->getNameAsCString()
204 << "' with floating point type '" << drCond->getType().getAsString()
205 << "' should not be used as a loop counter";
206
207 ranges.push_back(drCond->getSourceRange());
208 ranges.push_back(drInc->getSourceRange());
209
210 const char *bugType = "Floating point variable used as loop counter";
211 BR.EmitBasicReport(bugType, "Security", os.str().c_str(),
212 FS->getLocStart(), ranges.data(), ranges.size());
Ted Kremenekdbfb5f82009-07-23 01:07:19 +0000213}
214
215//===----------------------------------------------------------------------===//
Ted Kremenekefcbb152009-07-23 22:29:41 +0000216// Check: Any use of 'gets' is insecure.
217// Originally: <rdar://problem/6335715>
218// Implements (part of): 300-BSI (buildsecurityin.us-cert.gov)
219//===----------------------------------------------------------------------===//
220
221void WalkAST::CheckCall_gets(const CallExpr *CE, const FunctionDecl *FD) {
222 if (FD->getIdentifier() != GetIdentifier(II_gets, "gets"))
223 return;
224
225 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FD->getType());
226 if (!FTP)
227 return;
228
229 // Verify that the function takes a single argument.
230 if (FTP->getNumArgs() != 1)
231 return;
232
233 // Is the argument a 'char*'?
234 const PointerType *PT = dyn_cast<PointerType>(FTP->getArgType(0));
235 if (!PT)
236 return;
237
238 if (PT->getPointeeType().getUnqualifiedType() != BR.getContext().CharTy)
239 return;
240
241 // Issue a warning.
242 SourceRange R = CE->getCallee()->getSourceRange();
243 BR.EmitBasicReport("Potential buffer overflow in call to 'gets'",
244 "Security",
245 "Call to function 'gets' is extremely insecure as it can "
246 "always result in a buffer overflow",
247 CE->getLocStart(), &R, 1);
248}
249
250//===----------------------------------------------------------------------===//
Ted Kremenek24650472009-09-02 02:47:41 +0000251// Check: Linear congruent random number generators should not be used
252// Originally: <rdar://problem/63371000>
253// CWE-338: Use of cryptographically weak prng
254//===----------------------------------------------------------------------===//
255
256void WalkAST::CheckCall_rand(const CallExpr *CE, const FunctionDecl *FD) {
257 if (II_rand[0] == NULL) {
258 // This check applies to these functions
259 static const char * const identifiers[num_rands] = {
260 "drand48", "erand48", "jrand48", "lrand48", "mrand48", "nrand48",
261 "lcong48",
262 "rand", "rand_r"
263 };
264
265 for (size_t i = 0; i < num_rands; i++)
266 II_rand[i] = &BR.getContext().Idents.get(identifiers[i]);
267 }
268
269 const IdentifierInfo *id = FD->getIdentifier();
270 size_t identifierid;
271
272 for (identifierid = 0; identifierid < num_rands; identifierid++)
273 if (id == II_rand[identifierid])
274 break;
275
276 if (identifierid >= num_rands)
277 return;
278
279 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FD->getType());
280 if (!FTP)
281 return;
282
283 if (FTP->getNumArgs() == 1) {
284 // Is the argument an 'unsigned short *'?
285 // (Actually any integer type is allowed.)
286 const PointerType *PT = dyn_cast<PointerType>(FTP->getArgType(0));
287 if (!PT)
288 return;
289
290 if (! PT->getPointeeType()->isIntegerType())
291 return;
292 }
293 else if (FTP->getNumArgs() != 0)
294 return;
295
296 // Issue a warning.
297 std::string buf1;
298 llvm::raw_string_ostream os1(buf1);
299 os1 << "'" << FD->getNameAsString() << "' is a poor random number generator";
300
301 std::string buf2;
302 llvm::raw_string_ostream os2(buf2);
303 os2 << "Function '" << FD->getNameAsString()
304 << "' is obsolete because it implements a poor random number generator."
305 << " Use 'arc4random' instead";
306
307 SourceRange R = CE->getCallee()->getSourceRange();
308
309 BR.EmitBasicReport(os1.str().c_str(), "Security", os2.str().c_str(),
310 CE->getLocStart(), &R, 1);
311}
312
313//===----------------------------------------------------------------------===//
314// Check: 'random' should not be used
315// Originally: <rdar://problem/63371000>
316//===----------------------------------------------------------------------===//
317
318void WalkAST::CheckCall_random(const CallExpr *CE, const FunctionDecl *FD) {
319 if (FD->getIdentifier() != GetIdentifier(II_random, "random"))
320 return;
321
322 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FD->getType());
323 if (!FTP)
324 return;
325
326 // Verify that the function takes no argument.
327 if (FTP->getNumArgs() != 0)
328 return;
329
330 // Issue a warning.
331 SourceRange R = CE->getCallee()->getSourceRange();
332 BR.EmitBasicReport("'random' is not a secure random number generator",
333 "Security",
334 "The 'random' function produces a sequence of values that "
335 "an adversary may be able to predict. Use 'arc4random' "
336 "instead",
337 CE->getLocStart(), &R, 1);
338}
339
340//===----------------------------------------------------------------------===//
Ted Kremenek65a81a92009-08-28 00:08:09 +0000341// Check: Should check whether privileges are dropped successfully.
342// Originally: <rdar://problem/6337132>
343//===----------------------------------------------------------------------===//
344
345void WalkAST::CheckUncheckedReturnValue(CallExpr *CE) {
346 const FunctionDecl *FD = CE->getDirectCallee();
347 if (!FD)
348 return;
349
350 if (II_setid[0] == NULL) {
Ted Kremenek24650472009-09-02 02:47:41 +0000351 static const char * const identifiers[num_setids] = {
Ted Kremenek65a81a92009-08-28 00:08:09 +0000352 "setuid", "setgid", "seteuid", "setegid",
353 "setreuid", "setregid"
354 };
355
Ted Kremenek24650472009-09-02 02:47:41 +0000356 for (size_t i = 0; i < num_setids; i++)
Ted Kremenek65a81a92009-08-28 00:08:09 +0000357 II_setid[i] = &BR.getContext().Idents.get(identifiers[i]);
358 }
359
360 const IdentifierInfo *id = FD->getIdentifier();
361 size_t identifierid;
362
Ted Kremenek24650472009-09-02 02:47:41 +0000363 for (identifierid = 0; identifierid < num_setids; identifierid++)
Ted Kremenek65a81a92009-08-28 00:08:09 +0000364 if (id == II_setid[identifierid])
365 break;
366
Ted Kremenek24650472009-09-02 02:47:41 +0000367 if (identifierid >= num_setids)
Ted Kremenek65a81a92009-08-28 00:08:09 +0000368 return;
369
370 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FD->getType());
371 if (!FTP)
372 return;
373
Ted Kremeneka8187832009-08-28 00:24:55 +0000374 // Verify that the function takes one or two arguments (depending on
375 // the function).
Ted Kremenek65a81a92009-08-28 00:08:09 +0000376 if (FTP->getNumArgs() != (identifierid < 4 ? 1 : 2))
377 return;
378
379 // The arguments must be integers.
380 for (unsigned i = 0; i < FTP->getNumArgs(); i++)
381 if (! FTP->getArgType(i)->isIntegerType())
382 return;
383
384 // Issue a warning.
385 std::string buf1;
386 llvm::raw_string_ostream os1(buf1);
387 os1 << "Return value is not checked in call to '" << FD->getNameAsString()
388 << "'";
389
390 std::string buf2;
391 llvm::raw_string_ostream os2(buf2);
392 os2 << "The return value from the call to '" << FD->getNameAsString()
393 << "' is not checked. If an error occurs in '"
394 << FD->getNameAsString()
395 << "', the following code may execute with unexpected privileges";
396
397 SourceRange R = CE->getCallee()->getSourceRange();
398
399 BR.EmitBasicReport(os1.str().c_str(), "Security", os2.str().c_str(),
400 CE->getLocStart(), &R, 1);
401}
402
403//===----------------------------------------------------------------------===//
Ted Kremenekdbfb5f82009-07-23 01:07:19 +0000404// Entry point for check.
405//===----------------------------------------------------------------------===//
406
Ted Kremenek23760022009-08-21 23:58:43 +0000407void clang::CheckSecuritySyntaxOnly(const Decl *D, BugReporter &BR) {
Ted Kremenekdbfb5f82009-07-23 01:07:19 +0000408 WalkAST walker(BR);
409 walker.Visit(D->getBody());
410}