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/GR/BugReporter/BugReporter.h"
16 #include "clang/GR/Checkers/LocalCheckers.h"
17 #include "clang/AST/StmtVisitor.h"
18 #include "llvm/Support/raw_ostream.h"
20 using namespace clang
;
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
;
30 class WalkAST
: public StmtVisitor
<WalkAST
> {
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
];
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())) {}
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
); }
55 void VisitChildren(Stmt
*S
);
58 IdentifierInfo
*GetIdentifier(IdentifierInfo
*& II
, const char *str
);
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
);
69 } // end anonymous namespace
71 //===----------------------------------------------------------------------===//
73 //===----------------------------------------------------------------------===//
75 IdentifierInfo
*WalkAST::GetIdentifier(IdentifierInfo
*& II
, const char *str
) {
77 II
= &BR
.getContext().Idents
.get(str
);
82 //===----------------------------------------------------------------------===//
84 //===----------------------------------------------------------------------===//
86 void WalkAST::VisitChildren(Stmt
*S
) {
87 for (Stmt::child_iterator I
= S
->child_begin(), E
= S
->child_end(); I
!=E
; ++I
)
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
);
98 CheckCall_rand(CE
, FD
);
99 CheckCall_random(CE
, FD
);
103 // Recurse and check children.
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
);
116 void WalkAST::VisitForStmt(ForStmt
*FS
) {
117 CheckLoopConditionForFloat(FS
);
119 // Recurse and check children.
123 //===----------------------------------------------------------------------===//
124 // Check: floating poing variable used as loop counter.
125 // Originally: <rdar://problem/6336718>
126 // Implements: CERT security coding advisory FLP-30.
127 //===----------------------------------------------------------------------===//
129 static const DeclRefExpr
*
130 GetIncrementedVar(const Expr
*expr
, const VarDecl
*x
, const VarDecl
*y
) {
131 expr
= expr
->IgnoreParenCasts();
133 if (const BinaryOperator
*B
= dyn_cast
<BinaryOperator
>(expr
)) {
134 if (!(B
->isAssignmentOp() || B
->isCompoundAssignmentOp() ||
135 B
->getOpcode() == BO_Comma
))
138 if (const DeclRefExpr
*lhs
= GetIncrementedVar(B
->getLHS(), x
, y
))
141 if (const DeclRefExpr
*rhs
= GetIncrementedVar(B
->getRHS(), x
, y
))
147 if (const DeclRefExpr
*DR
= dyn_cast
<DeclRefExpr
>(expr
)) {
148 const NamedDecl
*ND
= DR
->getDecl();
149 return ND
== x
|| ND
== y
? DR
: NULL
;
152 if (const UnaryOperator
*U
= dyn_cast
<UnaryOperator
>(expr
))
153 return U
->isIncrementDecrementOp()
154 ? GetIncrementedVar(U
->getSubExpr(), x
, y
) : NULL
;
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.
163 void WalkAST::CheckLoopConditionForFloat(const ForStmt
*FS
) {
164 // Does the loop have a condition?
165 const Expr
*condition
= FS
->getCond();
170 // Does the loop have an increment?
171 const Expr
*increment
= FS
->getInc();
176 // Strip away '()' and casts.
177 condition
= condition
->IgnoreParenCasts();
178 increment
= increment
->IgnoreParenCasts();
180 // Is the loop condition a comparison?
181 const BinaryOperator
*B
= dyn_cast
<BinaryOperator
>(condition
);
186 // Is this a comparison?
187 if (!(B
->isRelationalOp() || B
->isEqualityOp()))
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());
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
;
200 if (!drLHS
&& !drRHS
)
203 const VarDecl
*vdLHS
= drLHS
? dyn_cast
<VarDecl
>(drLHS
->getDecl()) : NULL
;
204 const VarDecl
*vdRHS
= drRHS
? dyn_cast
<VarDecl
>(drRHS
->getDecl()) : NULL
;
206 if (!vdLHS
&& !vdRHS
)
209 // Does either variable appear in increment?
210 const DeclRefExpr
*drInc
= GetIncrementedVar(increment
, vdLHS
, vdRHS
);
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
;
219 llvm::SmallVector
<SourceRange
, 2> ranges
;
220 llvm::SmallString
<256> sbuf
;
221 llvm::raw_svector_ostream
os(sbuf
);
223 os
<< "Variable '" << drCond
->getDecl()->getName()
224 << "' with floating point type '" << drCond
->getType().getAsString()
225 << "' should not be used as a loop counter";
227 ranges
.push_back(drCond
->getSourceRange());
228 ranges
.push_back(drInc
->getSourceRange());
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());
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 //===----------------------------------------------------------------------===//
242 void WalkAST::CheckCall_gets(const CallExpr
*CE
, const FunctionDecl
*FD
) {
243 if (FD
->getIdentifier() != GetIdentifier(II_gets
, "gets"))
246 const FunctionProtoType
*FPT
247 = dyn_cast
<FunctionProtoType
>(FD
->getType().IgnoreParens());
251 // Verify that the function takes a single argument.
252 if (FPT
->getNumArgs() != 1)
255 // Is the argument a 'char*'?
256 const PointerType
*PT
= dyn_cast
<PointerType
>(FPT
->getArgType(0));
260 if (PT
->getPointeeType().getUnqualifiedType() != BR
.getContext().CharTy
)
264 SourceRange R
= CE
->getCallee()->getSourceRange();
265 BR
.EmitBasicReport("Potential buffer overflow in call to 'gets'",
267 "Call to function 'gets' is extremely insecure as it can "
268 "always result in a buffer overflow",
269 CE
->getLocStart(), &R
, 1);
272 //===----------------------------------------------------------------------===//
273 // Check: Any use of 'getpwd' is insecure.
274 // CWE-477: Use of Obsolete Functions
275 //===----------------------------------------------------------------------===//
277 void WalkAST::CheckCall_getpw(const CallExpr
*CE
, const FunctionDecl
*FD
) {
278 if (FD
->getIdentifier() != GetIdentifier(II_getpw
, "getpw"))
281 const FunctionProtoType
*FPT
282 = dyn_cast
<FunctionProtoType
>(FD
->getType().IgnoreParens());
286 // Verify that the function takes two arguments.
287 if (FPT
->getNumArgs() != 2)
290 // Verify the first argument type is integer.
291 if (!FPT
->getArgType(0)->isIntegerType())
294 // Verify the second argument type is char*.
295 const PointerType
*PT
= dyn_cast
<PointerType
>(FPT
->getArgType(1));
299 if (PT
->getPointeeType().getUnqualifiedType() != BR
.getContext().CharTy
)
303 SourceRange R
= CE
->getCallee()->getSourceRange();
304 BR
.EmitBasicReport("Potential buffer overflow in call to 'getpw'",
306 "The getpw() function is dangerous as it may overflow the "
307 "provided buffer. It is obsoleted by getpwuid().",
308 CE
->getLocStart(), &R
, 1);
311 //===----------------------------------------------------------------------===//
312 // Check: Any use of 'mktemp' is insecure.It is obsoleted by mkstemp().
313 // CWE-377: Insecure Temporary File
314 //===----------------------------------------------------------------------===//
316 void WalkAST::CheckCall_mktemp(const CallExpr
*CE
, const FunctionDecl
*FD
) {
317 if (FD
->getIdentifier() != GetIdentifier(II_mktemp
, "mktemp"))
320 const FunctionProtoType
*FPT
321 = dyn_cast
<FunctionProtoType
>(FD
->getType().IgnoreParens());
325 // Verify that the funcion takes a single argument.
326 if (FPT
->getNumArgs() != 1)
329 // Verify that the argument is Pointer Type.
330 const PointerType
*PT
= dyn_cast
<PointerType
>(FPT
->getArgType(0));
334 // Verify that the argument is a 'char*'.
335 if (PT
->getPointeeType().getUnqualifiedType() != BR
.getContext().CharTy
)
339 SourceRange R
= CE
->getCallee()->getSourceRange();
340 BR
.EmitBasicReport("Potential insecure temporary file in call 'mktemp'",
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);
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 //===----------------------------------------------------------------------===//
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",
362 for (size_t i
= 0; i
< num_rands
; i
++)
363 II_rand
[i
] = &BR
.getContext().Idents
.get(identifiers
[i
]);
366 const IdentifierInfo
*id
= FD
->getIdentifier();
369 for (identifierid
= 0; identifierid
< num_rands
; identifierid
++)
370 if (id
== II_rand
[identifierid
])
373 if (identifierid
>= num_rands
)
376 const FunctionProtoType
*FTP
377 = dyn_cast
<FunctionProtoType
>(FD
->getType().IgnoreParens());
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));
388 if (! PT
->getPointeeType()->isIntegerType())
391 else if (FTP
->getNumArgs() != 0)
395 llvm::SmallString
<256> buf1
;
396 llvm::raw_svector_ostream
os1(buf1
);
397 os1
<< '\'' << FD
<< "' is a poor random number generator";
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";
405 SourceRange R
= CE
->getCallee()->getSourceRange();
406 BR
.EmitBasicReport(os1
.str(), "Security", os2
.str(),CE
->getLocStart(), &R
, 1);
409 //===----------------------------------------------------------------------===//
410 // Check: 'random' should not be used
411 // Originally: <rdar://problem/63371000>
412 //===----------------------------------------------------------------------===//
414 void WalkAST::CheckCall_random(const CallExpr
*CE
, const FunctionDecl
*FD
) {
415 if (FD
->getIdentifier() != GetIdentifier(II_random
, "random"))
418 const FunctionProtoType
*FTP
419 = dyn_cast
<FunctionProtoType
>(FD
->getType().IgnoreParens());
423 // Verify that the function takes no argument.
424 if (FTP
->getNumArgs() != 0)
428 SourceRange R
= CE
->getCallee()->getSourceRange();
429 BR
.EmitBasicReport("'random' is not a secure random number generator",
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);
436 //===----------------------------------------------------------------------===//
437 // Check: Should check whether privileges are dropped successfully.
438 // Originally: <rdar://problem/6337132>
439 //===----------------------------------------------------------------------===//
441 void WalkAST::CheckUncheckedReturnValue(CallExpr
*CE
) {
442 const FunctionDecl
*FD
= CE
->getDirectCallee();
446 if (II_setid
[0] == NULL
) {
447 static const char * const identifiers
[num_setids
] = {
448 "setuid", "setgid", "seteuid", "setegid",
449 "setreuid", "setregid"
452 for (size_t i
= 0; i
< num_setids
; i
++)
453 II_setid
[i
] = &BR
.getContext().Idents
.get(identifiers
[i
]);
456 const IdentifierInfo
*id
= FD
->getIdentifier();
459 for (identifierid
= 0; identifierid
< num_setids
; identifierid
++)
460 if (id
== II_setid
[identifierid
])
463 if (identifierid
>= num_setids
)
466 const FunctionProtoType
*FTP
467 = dyn_cast
<FunctionProtoType
>(FD
->getType().IgnoreParens());
471 // Verify that the function takes one or two arguments (depending on
473 if (FTP
->getNumArgs() != (identifierid
< 4 ? 1 : 2))
476 // The arguments must be integers.
477 for (unsigned i
= 0; i
< FTP
->getNumArgs(); i
++)
478 if (! FTP
->getArgType(i
)->isIntegerType())
482 llvm::SmallString
<256> buf1
;
483 llvm::raw_svector_ostream
os1(buf1
);
484 os1
<< "Return value is not checked in call to '" << FD
<< '\'';
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";
492 SourceRange R
= CE
->getCallee()->getSourceRange();
493 BR
.EmitBasicReport(os1
.str(), "Security", os2
.str(),CE
->getLocStart(), &R
, 1);
496 //===----------------------------------------------------------------------===//
497 // Entry point for check.
498 //===----------------------------------------------------------------------===//
500 void GR::CheckSecuritySyntaxOnly(const Decl
*D
, BugReporter
&BR
) {
502 walker
.Visit(D
->getBody());