1 //==- CheckSecuritySyntaxOnly.cpp - Basic security checks --------*- C++ -*-==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines a set of flow-insensitive security checks.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Basic/TargetInfo.h"
15 #include "clang/Checker/BugReporter/BugReporter.h"
16 #include "clang/Checker/Checkers/LocalCheckers.h"
17 #include "clang/AST/StmtVisitor.h"
18 #include "llvm/Support/raw_ostream.h"
20 using namespace clang
;
22 static bool isArc4RandomAvailable(const ASTContext
&Ctx
) {
23 const llvm::Triple
&T
= Ctx
.Target
.getTriple();
24 return T
.getVendor() == llvm::Triple::Apple
||
25 T
.getOS() == llvm::Triple::FreeBSD
;
29 class WalkAST
: public StmtVisitor
<WalkAST
> {
31 IdentifierInfo
*II_gets
;
32 IdentifierInfo
*II_getpw
;
33 IdentifierInfo
*II_mktemp
;
34 enum { num_rands
= 9 };
35 IdentifierInfo
*II_rand
[num_rands
];
36 IdentifierInfo
*II_random
;
37 enum { num_setids
= 6 };
38 IdentifierInfo
*II_setid
[num_setids
];
43 WalkAST(BugReporter
&br
) : BR(br
),
44 II_gets(0), II_getpw(0), II_mktemp(0),
45 II_rand(), II_random(0), II_setid(),
46 CheckRand(isArc4RandomAvailable(BR
.getContext())) {}
48 // Statement visitor methods.
49 void VisitCallExpr(CallExpr
*CE
);
50 void VisitForStmt(ForStmt
*S
);
51 void VisitCompoundStmt (CompoundStmt
*S
);
52 void VisitStmt(Stmt
*S
) { VisitChildren(S
); }
54 void VisitChildren(Stmt
*S
);
57 IdentifierInfo
*GetIdentifier(IdentifierInfo
*& II
, const char *str
);
59 // Checker-specific methods.
60 void CheckLoopConditionForFloat(const ForStmt
*FS
);
61 void CheckCall_gets(const CallExpr
*CE
, const FunctionDecl
*FD
);
62 void CheckCall_getpw(const CallExpr
*CE
, const FunctionDecl
*FD
);
63 void CheckCall_mktemp(const CallExpr
*CE
, const FunctionDecl
*FD
);
64 void CheckCall_rand(const CallExpr
*CE
, const FunctionDecl
*FD
);
65 void CheckCall_random(const CallExpr
*CE
, const FunctionDecl
*FD
);
66 void CheckUncheckedReturnValue(CallExpr
*CE
);
68 } // end anonymous namespace
70 //===----------------------------------------------------------------------===//
72 //===----------------------------------------------------------------------===//
74 IdentifierInfo
*WalkAST::GetIdentifier(IdentifierInfo
*& II
, const char *str
) {
76 II
= &BR
.getContext().Idents
.get(str
);
81 //===----------------------------------------------------------------------===//
83 //===----------------------------------------------------------------------===//
85 void WalkAST::VisitChildren(Stmt
*S
) {
86 for (Stmt::child_iterator I
= S
->child_begin(), E
= S
->child_end(); I
!=E
; ++I
)
91 void WalkAST::VisitCallExpr(CallExpr
*CE
) {
92 if (const FunctionDecl
*FD
= CE
->getDirectCallee()) {
93 CheckCall_gets(CE
, FD
);
94 CheckCall_getpw(CE
, FD
);
95 CheckCall_mktemp(CE
, FD
);
97 CheckCall_rand(CE
, FD
);
98 CheckCall_random(CE
, FD
);
102 // Recurse and check children.
106 void WalkAST::VisitCompoundStmt(CompoundStmt
*S
) {
107 for (Stmt::child_iterator I
= S
->child_begin(), E
= S
->child_end(); I
!=E
; ++I
)
108 if (Stmt
*child
= *I
) {
109 if (CallExpr
*CE
= dyn_cast
<CallExpr
>(child
))
110 CheckUncheckedReturnValue(CE
);
115 void WalkAST::VisitForStmt(ForStmt
*FS
) {
116 CheckLoopConditionForFloat(FS
);
118 // Recurse and check children.
122 //===----------------------------------------------------------------------===//
123 // Check: floating poing variable used as loop counter.
124 // Originally: <rdar://problem/6336718>
125 // Implements: CERT security coding advisory FLP-30.
126 //===----------------------------------------------------------------------===//
128 static const DeclRefExpr
*
129 GetIncrementedVar(const Expr
*expr
, const VarDecl
*x
, const VarDecl
*y
) {
130 expr
= expr
->IgnoreParenCasts();
132 if (const BinaryOperator
*B
= dyn_cast
<BinaryOperator
>(expr
)) {
133 if (!(B
->isAssignmentOp() || B
->isCompoundAssignmentOp() ||
134 B
->getOpcode() == BO_Comma
))
137 if (const DeclRefExpr
*lhs
= GetIncrementedVar(B
->getLHS(), x
, y
))
140 if (const DeclRefExpr
*rhs
= GetIncrementedVar(B
->getRHS(), x
, y
))
146 if (const DeclRefExpr
*DR
= dyn_cast
<DeclRefExpr
>(expr
)) {
147 const NamedDecl
*ND
= DR
->getDecl();
148 return ND
== x
|| ND
== y
? DR
: NULL
;
151 if (const UnaryOperator
*U
= dyn_cast
<UnaryOperator
>(expr
))
152 return U
->isIncrementDecrementOp()
153 ? GetIncrementedVar(U
->getSubExpr(), x
, y
) : NULL
;
158 /// CheckLoopConditionForFloat - This check looks for 'for' statements that
159 /// use a floating point variable as a loop counter.
160 /// CERT: FLP30-C, FLP30-CPP.
162 void WalkAST::CheckLoopConditionForFloat(const ForStmt
*FS
) {
163 // Does the loop have a condition?
164 const Expr
*condition
= FS
->getCond();
169 // Does the loop have an increment?
170 const Expr
*increment
= FS
->getInc();
175 // Strip away '()' and casts.
176 condition
= condition
->IgnoreParenCasts();
177 increment
= increment
->IgnoreParenCasts();
179 // Is the loop condition a comparison?
180 const BinaryOperator
*B
= dyn_cast
<BinaryOperator
>(condition
);
185 // Is this a comparison?
186 if (!(B
->isRelationalOp() || B
->isEqualityOp()))
189 // Are we comparing variables?
190 const DeclRefExpr
*drLHS
= dyn_cast
<DeclRefExpr
>(B
->getLHS()->IgnoreParens());
191 const DeclRefExpr
*drRHS
= dyn_cast
<DeclRefExpr
>(B
->getRHS()->IgnoreParens());
193 // Does at least one of the variables have a floating point type?
194 drLHS
= drLHS
&& drLHS
->getType()->isRealFloatingType() ? drLHS
: NULL
;
195 drRHS
= drRHS
&& drRHS
->getType()->isRealFloatingType() ? drRHS
: NULL
;
197 if (!drLHS
&& !drRHS
)
200 const VarDecl
*vdLHS
= drLHS
? dyn_cast
<VarDecl
>(drLHS
->getDecl()) : NULL
;
201 const VarDecl
*vdRHS
= drRHS
? dyn_cast
<VarDecl
>(drRHS
->getDecl()) : NULL
;
203 if (!vdLHS
&& !vdRHS
)
206 // Does either variable appear in increment?
207 const DeclRefExpr
*drInc
= GetIncrementedVar(increment
, vdLHS
, vdRHS
);
212 // Emit the error. First figure out which DeclRefExpr in the condition
213 // referenced the compared variable.
214 const DeclRefExpr
*drCond
= vdLHS
== drInc
->getDecl() ? drLHS
: drRHS
;
216 llvm::SmallVector
<SourceRange
, 2> ranges
;
217 llvm::SmallString
<256> sbuf
;
218 llvm::raw_svector_ostream
os(sbuf
);
220 os
<< "Variable '" << drCond
->getDecl()->getName()
221 << "' with floating point type '" << drCond
->getType().getAsString()
222 << "' should not be used as a loop counter";
224 ranges
.push_back(drCond
->getSourceRange());
225 ranges
.push_back(drInc
->getSourceRange());
227 const char *bugType
= "Floating point variable used as loop counter";
228 BR
.EmitBasicReport(bugType
, "Security", os
.str(),
229 FS
->getLocStart(), ranges
.data(), ranges
.size());
232 //===----------------------------------------------------------------------===//
233 // Check: Any use of 'gets' is insecure.
234 // Originally: <rdar://problem/6335715>
235 // Implements (part of): 300-BSI (buildsecurityin.us-cert.gov)
236 // CWE-242: Use of Inherently Dangerous Function
237 //===----------------------------------------------------------------------===//
239 void WalkAST::CheckCall_gets(const CallExpr
*CE
, const FunctionDecl
*FD
) {
240 if (FD
->getIdentifier() != GetIdentifier(II_gets
, "gets"))
243 const FunctionProtoType
*FPT
= dyn_cast
<FunctionProtoType
>(FD
->getType());
247 // Verify that the function takes a single argument.
248 if (FPT
->getNumArgs() != 1)
251 // Is the argument a 'char*'?
252 const PointerType
*PT
= dyn_cast
<PointerType
>(FPT
->getArgType(0));
256 if (PT
->getPointeeType().getUnqualifiedType() != BR
.getContext().CharTy
)
260 SourceRange R
= CE
->getCallee()->getSourceRange();
261 BR
.EmitBasicReport("Potential buffer overflow in call to 'gets'",
263 "Call to function 'gets' is extremely insecure as it can "
264 "always result in a buffer overflow",
265 CE
->getLocStart(), &R
, 1);
268 //===----------------------------------------------------------------------===//
269 // Check: Any use of 'getpwd' is insecure.
270 // CWE-477: Use of Obsolete Functions
271 //===----------------------------------------------------------------------===//
273 void WalkAST::CheckCall_getpw(const CallExpr
*CE
, const FunctionDecl
*FD
) {
274 if (FD
->getIdentifier() != GetIdentifier(II_getpw
, "getpw"))
277 const FunctionProtoType
*FPT
= dyn_cast
<FunctionProtoType
>(FD
->getType());
281 // Verify that the function takes two arguments.
282 if (FPT
->getNumArgs() != 2)
285 // Verify the first argument type is integer.
286 if (!FPT
->getArgType(0)->isIntegerType())
289 // Verify the second argument type is char*.
290 const PointerType
*PT
= dyn_cast
<PointerType
>(FPT
->getArgType(1));
294 if (PT
->getPointeeType().getUnqualifiedType() != BR
.getContext().CharTy
)
298 SourceRange R
= CE
->getCallee()->getSourceRange();
299 BR
.EmitBasicReport("Potential buffer overflow in call to 'getpw'",
301 "The getpw() function is dangerous as it may overflow the "
302 "provided buffer. It is obsoleted by getpwuid().",
303 CE
->getLocStart(), &R
, 1);
306 //===----------------------------------------------------------------------===//
307 // Check: Any use of 'mktemp' is insecure.It is obsoleted by mkstemp().
308 // CWE-377: Insecure Temporary File
309 //===----------------------------------------------------------------------===//
311 void WalkAST::CheckCall_mktemp(const CallExpr
*CE
, const FunctionDecl
*FD
) {
312 if (FD
->getIdentifier() != GetIdentifier(II_mktemp
, "mktemp"))
315 const FunctionProtoType
*FPT
= dyn_cast
<FunctionProtoType
>(FD
->getType());
319 // Verify that the funcion takes a single argument.
320 if (FPT
->getNumArgs() != 1)
323 // Verify that the argument is Pointer Type.
324 const PointerType
*PT
= dyn_cast
<PointerType
>(FPT
->getArgType(0));
328 // Verify that the argument is a 'char*'.
329 if (PT
->getPointeeType().getUnqualifiedType() != BR
.getContext().CharTy
)
333 SourceRange R
= CE
->getCallee()->getSourceRange();
334 BR
.EmitBasicReport("Potential insecure temporary file in call 'mktemp'",
336 "Call to function 'mktemp' is insecure as it always "
337 "creates or uses insecure temporary file. Use 'mkstemp' instead",
338 CE
->getLocStart(), &R
, 1);
341 //===----------------------------------------------------------------------===//
342 // Check: Linear congruent random number generators should not be used
343 // Originally: <rdar://problem/63371000>
344 // CWE-338: Use of cryptographically weak prng
345 //===----------------------------------------------------------------------===//
347 void WalkAST::CheckCall_rand(const CallExpr
*CE
, const FunctionDecl
*FD
) {
348 if (II_rand
[0] == NULL
) {
349 // This check applies to these functions
350 static const char * const identifiers
[num_rands
] = {
351 "drand48", "erand48", "jrand48", "lrand48", "mrand48", "nrand48",
356 for (size_t i
= 0; i
< num_rands
; i
++)
357 II_rand
[i
] = &BR
.getContext().Idents
.get(identifiers
[i
]);
360 const IdentifierInfo
*id
= FD
->getIdentifier();
363 for (identifierid
= 0; identifierid
< num_rands
; identifierid
++)
364 if (id
== II_rand
[identifierid
])
367 if (identifierid
>= num_rands
)
370 const FunctionProtoType
*FTP
= dyn_cast
<FunctionProtoType
>(FD
->getType());
374 if (FTP
->getNumArgs() == 1) {
375 // Is the argument an 'unsigned short *'?
376 // (Actually any integer type is allowed.)
377 const PointerType
*PT
= dyn_cast
<PointerType
>(FTP
->getArgType(0));
381 if (! PT
->getPointeeType()->isIntegerType())
384 else if (FTP
->getNumArgs() != 0)
388 llvm::SmallString
<256> buf1
;
389 llvm::raw_svector_ostream
os1(buf1
);
390 os1
<< '\'' << FD
<< "' is a poor random number generator";
392 llvm::SmallString
<256> buf2
;
393 llvm::raw_svector_ostream
os2(buf2
);
394 os2
<< "Function '" << FD
395 << "' is obsolete because it implements a poor random number generator."
396 << " Use 'arc4random' instead";
398 SourceRange R
= CE
->getCallee()->getSourceRange();
399 BR
.EmitBasicReport(os1
.str(), "Security", os2
.str(),CE
->getLocStart(), &R
, 1);
402 //===----------------------------------------------------------------------===//
403 // Check: 'random' should not be used
404 // Originally: <rdar://problem/63371000>
405 //===----------------------------------------------------------------------===//
407 void WalkAST::CheckCall_random(const CallExpr
*CE
, const FunctionDecl
*FD
) {
408 if (FD
->getIdentifier() != GetIdentifier(II_random
, "random"))
411 const FunctionProtoType
*FTP
= dyn_cast
<FunctionProtoType
>(FD
->getType());
415 // Verify that the function takes no argument.
416 if (FTP
->getNumArgs() != 0)
420 SourceRange R
= CE
->getCallee()->getSourceRange();
421 BR
.EmitBasicReport("'random' is not a secure random number generator",
423 "The 'random' function produces a sequence of values that "
424 "an adversary may be able to predict. Use 'arc4random' "
425 "instead", CE
->getLocStart(), &R
, 1);
428 //===----------------------------------------------------------------------===//
429 // Check: Should check whether privileges are dropped successfully.
430 // Originally: <rdar://problem/6337132>
431 //===----------------------------------------------------------------------===//
433 void WalkAST::CheckUncheckedReturnValue(CallExpr
*CE
) {
434 const FunctionDecl
*FD
= CE
->getDirectCallee();
438 if (II_setid
[0] == NULL
) {
439 static const char * const identifiers
[num_setids
] = {
440 "setuid", "setgid", "seteuid", "setegid",
441 "setreuid", "setregid"
444 for (size_t i
= 0; i
< num_setids
; i
++)
445 II_setid
[i
] = &BR
.getContext().Idents
.get(identifiers
[i
]);
448 const IdentifierInfo
*id
= FD
->getIdentifier();
451 for (identifierid
= 0; identifierid
< num_setids
; identifierid
++)
452 if (id
== II_setid
[identifierid
])
455 if (identifierid
>= num_setids
)
458 const FunctionProtoType
*FTP
= dyn_cast
<FunctionProtoType
>(FD
->getType());
462 // Verify that the function takes one or two arguments (depending on
464 if (FTP
->getNumArgs() != (identifierid
< 4 ? 1 : 2))
467 // The arguments must be integers.
468 for (unsigned i
= 0; i
< FTP
->getNumArgs(); i
++)
469 if (! FTP
->getArgType(i
)->isIntegerType())
473 llvm::SmallString
<256> buf1
;
474 llvm::raw_svector_ostream
os1(buf1
);
475 os1
<< "Return value is not checked in call to '" << FD
<< '\'';
477 llvm::SmallString
<256> buf2
;
478 llvm::raw_svector_ostream
os2(buf2
);
479 os2
<< "The return value from the call to '" << FD
480 << "' is not checked. If an error occurs in '" << FD
481 << "', the following code may execute with unexpected privileges";
483 SourceRange R
= CE
->getCallee()->getSourceRange();
484 BR
.EmitBasicReport(os1
.str(), "Security", os2
.str(),CE
->getLocStart(), &R
, 1);
487 //===----------------------------------------------------------------------===//
488 // Entry point for check.
489 //===----------------------------------------------------------------------===//
491 void clang::CheckSecuritySyntaxOnly(const Decl
*D
, BugReporter
&BR
) {
493 walker
.Visit(D
->getBody());