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 "ClangSACheckers.h"
15 #include "clang/StaticAnalyzer/Core/Checker.h"
16 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
17 #include "clang/Basic/TargetInfo.h"
18 #include "clang/AST/StmtVisitor.h"
19 #include "llvm/Support/raw_ostream.h"
20 #include "llvm/ADT/StringSwitch.h"
22 using namespace clang;
25 static bool isArc4RandomAvailable(const ASTContext &Ctx) {
26 const llvm::Triple &T = Ctx.Target.getTriple();
27 return T.getVendor() == llvm::Triple::Apple ||
28 T.getOS() == llvm::Triple::FreeBSD ||
29 T.getOS() == llvm::Triple::NetBSD ||
30 T.getOS() == llvm::Triple::OpenBSD ||
31 T.getOS() == llvm::Triple::DragonFly;
35 class WalkAST : public StmtVisitor<WalkAST> {
37 enum { num_setids = 6 };
38 IdentifierInfo *II_setid[num_setids];
43 WalkAST(BugReporter &br) : BR(br), II_setid(),
44 CheckRand(isArc4RandomAvailable(BR.getContext())) {}
46 // Statement visitor methods.
47 void VisitCallExpr(CallExpr *CE);
48 void VisitForStmt(ForStmt *S);
49 void VisitCompoundStmt (CompoundStmt *S);
50 void VisitStmt(Stmt *S) { VisitChildren(S); }
52 void VisitChildren(Stmt *S);
55 IdentifierInfo *getIdentifier(IdentifierInfo *& II, const char *str);
56 bool checkCall_strCommon(const CallExpr *CE, const FunctionDecl *FD);
58 typedef void (WalkAST::*FnCheck)(const CallExpr *,
59 const FunctionDecl *);
61 // Checker-specific methods.
62 void checkLoopConditionForFloat(const ForStmt *FS);
63 void checkCall_gets(const CallExpr *CE, const FunctionDecl *FD);
64 void checkCall_getpw(const CallExpr *CE, const FunctionDecl *FD);
65 void checkCall_mktemp(const CallExpr *CE, const FunctionDecl *FD);
66 void checkCall_strcpy(const CallExpr *CE, const FunctionDecl *FD);
67 void checkCall_strcat(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);
72 } // end anonymous namespace
74 //===----------------------------------------------------------------------===//
76 //===----------------------------------------------------------------------===//
78 IdentifierInfo *WalkAST::getIdentifier(IdentifierInfo *& II, const char *str) {
80 II = &BR.getContext().Idents.get(str);
85 //===----------------------------------------------------------------------===//
87 //===----------------------------------------------------------------------===//
89 void WalkAST::VisitChildren(Stmt *S) {
90 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
95 void WalkAST::VisitCallExpr(CallExpr *CE) {
97 const FunctionDecl *FD = CE->getDirectCallee();
102 // Get the name of the callee. If it's a builtin, strip off the prefix.
103 IdentifierInfo *II = FD->getIdentifier();
104 if (!II) // if no identifier, not a simple C function
106 llvm::StringRef Name = II->getName();
107 if (Name.startswith("__builtin_"))
108 Name = Name.substr(10);
110 // Set the evaluation function by switching on the callee name.
111 FnCheck evalFunction = llvm::StringSwitch<FnCheck>(Name)
112 .Case("gets", &WalkAST::checkCall_gets)
113 .Case("getpw", &WalkAST::checkCall_getpw)
114 .Case("mktemp", &WalkAST::checkCall_mktemp)
115 .Cases("strcpy", "__strcpy_chk", &WalkAST::checkCall_strcpy)
116 .Cases("strcat", "__strcat_chk", &WalkAST::checkCall_strcat)
117 .Case("drand48", &WalkAST::checkCall_rand)
118 .Case("erand48", &WalkAST::checkCall_rand)
119 .Case("jrand48", &WalkAST::checkCall_rand)
120 .Case("lrand48", &WalkAST::checkCall_rand)
121 .Case("mrand48", &WalkAST::checkCall_rand)
122 .Case("nrand48", &WalkAST::checkCall_rand)
123 .Case("lcong48", &WalkAST::checkCall_rand)
124 .Case("rand", &WalkAST::checkCall_rand)
125 .Case("rand_r", &WalkAST::checkCall_rand)
126 .Case("random", &WalkAST::checkCall_random)
129 // If the callee isn't defined, it is not of security concern.
130 // Check and evaluate the call.
132 (this->*evalFunction)(CE, FD);
134 // Recurse and check children.
138 void WalkAST::VisitCompoundStmt(CompoundStmt *S) {
139 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
140 if (Stmt *child = *I) {
141 if (CallExpr *CE = dyn_cast<CallExpr>(child))
142 checkUncheckedReturnValue(CE);
147 void WalkAST::VisitForStmt(ForStmt *FS) {
148 checkLoopConditionForFloat(FS);
150 // Recurse and check children.
154 //===----------------------------------------------------------------------===//
155 // Check: floating poing variable used as loop counter.
156 // Originally: <rdar://problem/6336718>
157 // Implements: CERT security coding advisory FLP-30.
158 //===----------------------------------------------------------------------===//
160 static const DeclRefExpr*
161 getIncrementedVar(const Expr *expr, const VarDecl *x, const VarDecl *y) {
162 expr = expr->IgnoreParenCasts();
164 if (const BinaryOperator *B = dyn_cast<BinaryOperator>(expr)) {
165 if (!(B->isAssignmentOp() || B->isCompoundAssignmentOp() ||
166 B->getOpcode() == BO_Comma))
169 if (const DeclRefExpr *lhs = getIncrementedVar(B->getLHS(), x, y))
172 if (const DeclRefExpr *rhs = getIncrementedVar(B->getRHS(), x, y))
178 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(expr)) {
179 const NamedDecl *ND = DR->getDecl();
180 return ND == x || ND == y ? DR : NULL;
183 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(expr))
184 return U->isIncrementDecrementOp()
185 ? getIncrementedVar(U->getSubExpr(), x, y) : NULL;
190 /// CheckLoopConditionForFloat - This check looks for 'for' statements that
191 /// use a floating point variable as a loop counter.
192 /// CERT: FLP30-C, FLP30-CPP.
194 void WalkAST::checkLoopConditionForFloat(const ForStmt *FS) {
195 // Does the loop have a condition?
196 const Expr *condition = FS->getCond();
201 // Does the loop have an increment?
202 const Expr *increment = FS->getInc();
207 // Strip away '()' and casts.
208 condition = condition->IgnoreParenCasts();
209 increment = increment->IgnoreParenCasts();
211 // Is the loop condition a comparison?
212 const BinaryOperator *B = dyn_cast<BinaryOperator>(condition);
217 // Is this a comparison?
218 if (!(B->isRelationalOp() || B->isEqualityOp()))
221 // Are we comparing variables?
222 const DeclRefExpr *drLHS =
223 dyn_cast<DeclRefExpr>(B->getLHS()->IgnoreParenLValueCasts());
224 const DeclRefExpr *drRHS =
225 dyn_cast<DeclRefExpr>(B->getRHS()->IgnoreParenLValueCasts());
227 // Does at least one of the variables have a floating point type?
228 drLHS = drLHS && drLHS->getType()->isRealFloatingType() ? drLHS : NULL;
229 drRHS = drRHS && drRHS->getType()->isRealFloatingType() ? drRHS : NULL;
231 if (!drLHS && !drRHS)
234 const VarDecl *vdLHS = drLHS ? dyn_cast<VarDecl>(drLHS->getDecl()) : NULL;
235 const VarDecl *vdRHS = drRHS ? dyn_cast<VarDecl>(drRHS->getDecl()) : NULL;
237 if (!vdLHS && !vdRHS)
240 // Does either variable appear in increment?
241 const DeclRefExpr *drInc = getIncrementedVar(increment, vdLHS, vdRHS);
246 // Emit the error. First figure out which DeclRefExpr in the condition
247 // referenced the compared variable.
248 const DeclRefExpr *drCond = vdLHS == drInc->getDecl() ? drLHS : drRHS;
250 llvm::SmallVector<SourceRange, 2> ranges;
251 llvm::SmallString<256> sbuf;
252 llvm::raw_svector_ostream os(sbuf);
254 os << "Variable '" << drCond->getDecl()->getName()
255 << "' with floating point type '" << drCond->getType().getAsString()
256 << "' should not be used as a loop counter";
258 ranges.push_back(drCond->getSourceRange());
259 ranges.push_back(drInc->getSourceRange());
261 const char *bugType = "Floating point variable used as loop counter";
262 BR.EmitBasicReport(bugType, "Security", os.str(),
263 FS->getLocStart(), ranges.data(), ranges.size());
266 //===----------------------------------------------------------------------===//
267 // Check: Any use of 'gets' is insecure.
268 // Originally: <rdar://problem/6335715>
269 // Implements (part of): 300-BSI (buildsecurityin.us-cert.gov)
270 // CWE-242: Use of Inherently Dangerous Function
271 //===----------------------------------------------------------------------===//
273 void WalkAST::checkCall_gets(const CallExpr *CE, const FunctionDecl *FD) {
274 const FunctionProtoType *FPT
275 = dyn_cast<FunctionProtoType>(FD->getType().IgnoreParens());
279 // Verify that the function takes a single argument.
280 if (FPT->getNumArgs() != 1)
283 // Is the argument a 'char*'?
284 const PointerType *PT = dyn_cast<PointerType>(FPT->getArgType(0));
288 if (PT->getPointeeType().getUnqualifiedType() != BR.getContext().CharTy)
292 SourceRange R = CE->getCallee()->getSourceRange();
293 BR.EmitBasicReport("Potential buffer overflow in call to 'gets'",
295 "Call to function 'gets' is extremely insecure as it can "
296 "always result in a buffer overflow",
297 CE->getLocStart(), &R, 1);
300 //===----------------------------------------------------------------------===//
301 // Check: Any use of 'getpwd' is insecure.
302 // CWE-477: Use of Obsolete Functions
303 //===----------------------------------------------------------------------===//
305 void WalkAST::checkCall_getpw(const CallExpr *CE, const FunctionDecl *FD) {
306 const FunctionProtoType *FPT
307 = dyn_cast<FunctionProtoType>(FD->getType().IgnoreParens());
311 // Verify that the function takes two arguments.
312 if (FPT->getNumArgs() != 2)
315 // Verify the first argument type is integer.
316 if (!FPT->getArgType(0)->isIntegerType())
319 // Verify the second argument type is char*.
320 const PointerType *PT = dyn_cast<PointerType>(FPT->getArgType(1));
324 if (PT->getPointeeType().getUnqualifiedType() != BR.getContext().CharTy)
328 SourceRange R = CE->getCallee()->getSourceRange();
329 BR.EmitBasicReport("Potential buffer overflow in call to 'getpw'",
331 "The getpw() function is dangerous as it may overflow the "
332 "provided buffer. It is obsoleted by getpwuid().",
333 CE->getLocStart(), &R, 1);
336 //===----------------------------------------------------------------------===//
337 // Check: Any use of 'mktemp' is insecure.It is obsoleted by mkstemp().
338 // CWE-377: Insecure Temporary File
339 //===----------------------------------------------------------------------===//
341 void WalkAST::checkCall_mktemp(const CallExpr *CE, const FunctionDecl *FD) {
342 const FunctionProtoType *FPT
343 = dyn_cast<FunctionProtoType>(FD->getType().IgnoreParens());
347 // Verify that the function takes a single argument.
348 if (FPT->getNumArgs() != 1)
351 // Verify that the argument is Pointer Type.
352 const PointerType *PT = dyn_cast<PointerType>(FPT->getArgType(0));
356 // Verify that the argument is a 'char*'.
357 if (PT->getPointeeType().getUnqualifiedType() != BR.getContext().CharTy)
361 SourceRange R = CE->getCallee()->getSourceRange();
362 BR.EmitBasicReport("Potential insecure temporary file in call 'mktemp'",
364 "Call to function 'mktemp' is insecure as it always "
365 "creates or uses insecure temporary file. Use 'mkstemp' instead",
366 CE->getLocStart(), &R, 1);
369 //===----------------------------------------------------------------------===//
370 // Check: Any use of 'strcpy' is insecure.
372 // CWE-119: Improper Restriction of Operations within
373 // the Bounds of a Memory Buffer
374 //===----------------------------------------------------------------------===//
375 void WalkAST::checkCall_strcpy(const CallExpr *CE, const FunctionDecl *FD) {
376 if (!checkCall_strCommon(CE, FD))
380 SourceRange R = CE->getCallee()->getSourceRange();
381 BR.EmitBasicReport("Potential insecure memory buffer bounds restriction in "
384 "Call to function 'strcpy' is insecure as it does not "
385 "provide bounding of the memory buffer. Replace "
386 "unbounded copy functions with analogous functions that "
387 "support length arguments such as 'strncpy'. CWE-119.",
388 CE->getLocStart(), &R, 1);
391 //===----------------------------------------------------------------------===//
392 // Check: Any use of 'strcat' is insecure.
394 // CWE-119: Improper Restriction of Operations within
395 // the Bounds of a Memory Buffer
396 //===----------------------------------------------------------------------===//
397 void WalkAST::checkCall_strcat(const CallExpr *CE, const FunctionDecl *FD) {
398 if (!checkCall_strCommon(CE, FD))
402 SourceRange R = CE->getCallee()->getSourceRange();
403 BR.EmitBasicReport("Potential insecure memory buffer bounds restriction in "
406 "Call to function 'strcat' is insecure as it does not "
407 "provide bounding of the memory buffer. Replace "
408 "unbounded copy functions with analogous functions that "
409 "support length arguments such as 'strncat'. CWE-119.",
410 CE->getLocStart(), &R, 1);
413 //===----------------------------------------------------------------------===//
414 // Common check for str* functions with no bounds parameters.
415 //===----------------------------------------------------------------------===//
416 bool WalkAST::checkCall_strCommon(const CallExpr *CE, const FunctionDecl *FD) {
417 const FunctionProtoType *FPT
418 = dyn_cast<FunctionProtoType>(FD->getType().IgnoreParens());
422 // Verify the function takes two arguments, three in the _chk version.
423 int numArgs = FPT->getNumArgs();
424 if (numArgs != 2 && numArgs != 3)
427 // Verify the type for both arguments.
428 for (int i = 0; i < 2; i++) {
429 // Verify that the arguments are pointers.
430 const PointerType *PT = dyn_cast<PointerType>(FPT->getArgType(i));
434 // Verify that the argument is a 'char*'.
435 if (PT->getPointeeType().getUnqualifiedType() != BR.getContext().CharTy)
442 //===----------------------------------------------------------------------===//
443 // Check: Linear congruent random number generators should not be used
444 // Originally: <rdar://problem/63371000>
445 // CWE-338: Use of cryptographically weak prng
446 //===----------------------------------------------------------------------===//
448 void WalkAST::checkCall_rand(const CallExpr *CE, const FunctionDecl *FD) {
452 const FunctionProtoType *FTP
453 = dyn_cast<FunctionProtoType>(FD->getType().IgnoreParens());
457 if (FTP->getNumArgs() == 1) {
458 // Is the argument an 'unsigned short *'?
459 // (Actually any integer type is allowed.)
460 const PointerType *PT = dyn_cast<PointerType>(FTP->getArgType(0));
464 if (! PT->getPointeeType()->isIntegerType())
467 else if (FTP->getNumArgs() != 0)
471 llvm::SmallString<256> buf1;
472 llvm::raw_svector_ostream os1(buf1);
473 os1 << '\'' << FD << "' is a poor random number generator";
475 llvm::SmallString<256> buf2;
476 llvm::raw_svector_ostream os2(buf2);
477 os2 << "Function '" << FD
478 << "' is obsolete because it implements a poor random number generator."
479 << " Use 'arc4random' instead";
481 SourceRange R = CE->getCallee()->getSourceRange();
482 BR.EmitBasicReport(os1.str(), "Security", os2.str(),CE->getLocStart(), &R, 1);
485 //===----------------------------------------------------------------------===//
486 // Check: 'random' should not be used
487 // Originally: <rdar://problem/63371000>
488 //===----------------------------------------------------------------------===//
490 void WalkAST::checkCall_random(const CallExpr *CE, const FunctionDecl *FD) {
494 const FunctionProtoType *FTP
495 = dyn_cast<FunctionProtoType>(FD->getType().IgnoreParens());
499 // Verify that the function takes no argument.
500 if (FTP->getNumArgs() != 0)
504 SourceRange R = CE->getCallee()->getSourceRange();
505 BR.EmitBasicReport("'random' is not a secure random number generator",
507 "The 'random' function produces a sequence of values that "
508 "an adversary may be able to predict. Use 'arc4random' "
509 "instead", CE->getLocStart(), &R, 1);
512 //===----------------------------------------------------------------------===//
513 // Check: Should check whether privileges are dropped successfully.
514 // Originally: <rdar://problem/6337132>
515 //===----------------------------------------------------------------------===//
517 void WalkAST::checkUncheckedReturnValue(CallExpr *CE) {
518 const FunctionDecl *FD = CE->getDirectCallee();
522 if (II_setid[0] == NULL) {
523 static const char * const identifiers[num_setids] = {
524 "setuid", "setgid", "seteuid", "setegid",
525 "setreuid", "setregid"
528 for (size_t i = 0; i < num_setids; i++)
529 II_setid[i] = &BR.getContext().Idents.get(identifiers[i]);
532 const IdentifierInfo *id = FD->getIdentifier();
535 for (identifierid = 0; identifierid < num_setids; identifierid++)
536 if (id == II_setid[identifierid])
539 if (identifierid >= num_setids)
542 const FunctionProtoType *FTP
543 = dyn_cast<FunctionProtoType>(FD->getType().IgnoreParens());
547 // Verify that the function takes one or two arguments (depending on
549 if (FTP->getNumArgs() != (identifierid < 4 ? 1 : 2))
552 // The arguments must be integers.
553 for (unsigned i = 0; i < FTP->getNumArgs(); i++)
554 if (! FTP->getArgType(i)->isIntegerType())
558 llvm::SmallString<256> buf1;
559 llvm::raw_svector_ostream os1(buf1);
560 os1 << "Return value is not checked in call to '" << FD << '\'';
562 llvm::SmallString<256> buf2;
563 llvm::raw_svector_ostream os2(buf2);
564 os2 << "The return value from the call to '" << FD
565 << "' is not checked. If an error occurs in '" << FD
566 << "', the following code may execute with unexpected privileges";
568 SourceRange R = CE->getCallee()->getSourceRange();
569 BR.EmitBasicReport(os1.str(), "Security", os2.str(),CE->getLocStart(), &R, 1);
572 //===----------------------------------------------------------------------===//
573 // SecuritySyntaxChecker
574 //===----------------------------------------------------------------------===//
577 class SecuritySyntaxChecker : public Checker<check::ASTCodeBody> {
579 void checkASTCodeBody(const Decl *D, AnalysisManager& mgr,
580 BugReporter &BR) const {
582 walker.Visit(D->getBody());
587 void ento::registerSecuritySyntaxChecker(CheckerManager &mgr) {
588 mgr.registerChecker<SecuritySyntaxChecker>();