1 //==- 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 "ClangSACheckers.h" 15 #include "clang/Analysis/AnalysisContext.h" 16 #include "clang/AST/StmtVisitor.h" 17 #include "clang/Basic/TargetInfo.h" 18 #include "clang/StaticAnalyzer/Core/Checker.h" 19 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h" 20 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h" 21 #include "llvm/ADT/SmallString.h" 22 #include "llvm/ADT/StringSwitch.h" 23 #include "llvm/Support/raw_ostream.h" 24 25 using namespace clang; 26 using namespace ento; 27 28 static bool isArc4RandomAvailable(const ASTContext &Ctx) { 29 const llvm::Triple &T = Ctx.getTargetInfo().getTriple(); 30 return T.getVendor() == llvm::Triple::Apple || 31 T.getOS() == llvm::Triple::FreeBSD || 32 T.getOS() == llvm::Triple::NetBSD || 33 T.getOS() == llvm::Triple::OpenBSD || 34 T.getOS() == llvm::Triple::DragonFly; 35 } 36 37 namespace { 38 struct DefaultBool { 39 bool val; 40 DefaultBool() : val(false) {} 41 operator bool() const { return val; } 42 DefaultBool &operator=(bool b) { val = b; return *this; } 43 }; 44 45 struct ChecksFilter { 46 DefaultBool check_gets; 47 DefaultBool check_getpw; 48 DefaultBool check_mktemp; 49 DefaultBool check_mkstemp; 50 DefaultBool check_strcpy; 51 DefaultBool check_rand; 52 DefaultBool check_vfork; 53 DefaultBool check_FloatLoopCounter; 54 DefaultBool check_UncheckedReturn; 55 }; 56 57 class WalkAST : public StmtVisitor<WalkAST> { 58 BugReporter &BR; 59 AnalysisDeclContext* AC; 60 enum { num_setids = 6 }; 61 IdentifierInfo *II_setid[num_setids]; 62 63 const bool CheckRand; 64 const ChecksFilter &filter; 65 66 public: 67 WalkAST(BugReporter &br, AnalysisDeclContext* ac, 68 const ChecksFilter &f) 69 : BR(br), AC(ac), II_setid(), 70 CheckRand(isArc4RandomAvailable(BR.getContext())), 71 filter(f) {} 72 73 // Statement visitor methods. 74 void VisitCallExpr(CallExpr *CE); 75 void VisitForStmt(ForStmt *S); 76 void VisitCompoundStmt (CompoundStmt *S); 77 void VisitStmt(Stmt *S) { VisitChildren(S); } 78 79 void VisitChildren(Stmt *S); 80 81 // Helpers. 82 bool checkCall_strCommon(const CallExpr *CE, const FunctionDecl *FD); 83 84 typedef void (WalkAST::*FnCheck)(const CallExpr *, 85 const FunctionDecl *); 86 87 // Checker-specific methods. 88 void checkLoopConditionForFloat(const ForStmt *FS); 89 void checkCall_gets(const CallExpr *CE, const FunctionDecl *FD); 90 void checkCall_getpw(const CallExpr *CE, const FunctionDecl *FD); 91 void checkCall_mktemp(const CallExpr *CE, const FunctionDecl *FD); 92 void checkCall_mkstemp(const CallExpr *CE, const FunctionDecl *FD); 93 void checkCall_strcpy(const CallExpr *CE, const FunctionDecl *FD); 94 void checkCall_strcat(const CallExpr *CE, const FunctionDecl *FD); 95 void checkCall_rand(const CallExpr *CE, const FunctionDecl *FD); 96 void checkCall_random(const CallExpr *CE, const FunctionDecl *FD); 97 void checkCall_vfork(const CallExpr *CE, const FunctionDecl *FD); 98 void checkUncheckedReturnValue(CallExpr *CE); 99 }; 100 } // end anonymous namespace 101 102 //===----------------------------------------------------------------------===// 103 // AST walking. 104 //===----------------------------------------------------------------------===// 105 106 void WalkAST::VisitChildren(Stmt *S) { 107 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I) 108 if (Stmt *child = *I) 109 Visit(child); 110 } 111 112 void WalkAST::VisitCallExpr(CallExpr *CE) { 113 // Get the callee. 114 const FunctionDecl *FD = CE->getDirectCallee(); 115 116 if (!FD) 117 return; 118 119 // Get the name of the callee. If it's a builtin, strip off the prefix. 120 IdentifierInfo *II = FD->getIdentifier(); 121 if (!II) // if no identifier, not a simple C function 122 return; 123 StringRef Name = II->getName(); 124 if (Name.startswith("__builtin_")) 125 Name = Name.substr(10); 126 127 // Set the evaluation function by switching on the callee name. 128 FnCheck evalFunction = llvm::StringSwitch<FnCheck>(Name) 129 .Case("gets", &WalkAST::checkCall_gets) 130 .Case("getpw", &WalkAST::checkCall_getpw) 131 .Case("mktemp", &WalkAST::checkCall_mktemp) 132 .Case("mkstemp", &WalkAST::checkCall_mkstemp) 133 .Case("mkdtemp", &WalkAST::checkCall_mkstemp) 134 .Case("mkstemps", &WalkAST::checkCall_mkstemp) 135 .Cases("strcpy", "__strcpy_chk", &WalkAST::checkCall_strcpy) 136 .Cases("strcat", "__strcat_chk", &WalkAST::checkCall_strcat) 137 .Case("drand48", &WalkAST::checkCall_rand) 138 .Case("erand48", &WalkAST::checkCall_rand) 139 .Case("jrand48", &WalkAST::checkCall_rand) 140 .Case("lrand48", &WalkAST::checkCall_rand) 141 .Case("mrand48", &WalkAST::checkCall_rand) 142 .Case("nrand48", &WalkAST::checkCall_rand) 143 .Case("lcong48", &WalkAST::checkCall_rand) 144 .Case("rand", &WalkAST::checkCall_rand) 145 .Case("rand_r", &WalkAST::checkCall_rand) 146 .Case("random", &WalkAST::checkCall_random) 147 .Case("vfork", &WalkAST::checkCall_vfork) 148 .Default(NULL); 149 150 // If the callee isn't defined, it is not of security concern. 151 // Check and evaluate the call. 152 if (evalFunction) 153 (this->*evalFunction)(CE, FD); 154 155 // Recurse and check children. 156 VisitChildren(CE); 157 } 158 159 void WalkAST::VisitCompoundStmt(CompoundStmt *S) { 160 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I) 161 if (Stmt *child = *I) { 162 if (CallExpr *CE = dyn_cast<CallExpr>(child)) 163 checkUncheckedReturnValue(CE); 164 Visit(child); 165 } 166 } 167 168 void WalkAST::VisitForStmt(ForStmt *FS) { 169 checkLoopConditionForFloat(FS); 170 171 // Recurse and check children. 172 VisitChildren(FS); 173 } 174 175 //===----------------------------------------------------------------------===// 176 // Check: floating poing variable used as loop counter. 177 // Originally: <rdar://problem/6336718> 178 // Implements: CERT security coding advisory FLP-30. 179 //===----------------------------------------------------------------------===// 180 181 static const DeclRefExpr* 182 getIncrementedVar(const Expr *expr, const VarDecl *x, const VarDecl *y) { 183 expr = expr->IgnoreParenCasts(); 184 185 if (const BinaryOperator *B = dyn_cast<BinaryOperator>(expr)) { 186 if (!(B->isAssignmentOp() || B->isCompoundAssignmentOp() || 187 B->getOpcode() == BO_Comma)) 188 return NULL; 189 190 if (const DeclRefExpr *lhs = getIncrementedVar(B->getLHS(), x, y)) 191 return lhs; 192 193 if (const DeclRefExpr *rhs = getIncrementedVar(B->getRHS(), x, y)) 194 return rhs; 195 196 return NULL; 197 } 198 199 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(expr)) { 200 const NamedDecl *ND = DR->getDecl(); 201 return ND == x || ND == y ? DR : NULL; 202 } 203 204 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(expr)) 205 return U->isIncrementDecrementOp() 206 ? getIncrementedVar(U->getSubExpr(), x, y) : NULL; 207 208 return NULL; 209 } 210 211 /// CheckLoopConditionForFloat - This check looks for 'for' statements that 212 /// use a floating point variable as a loop counter. 213 /// CERT: FLP30-C, FLP30-CPP. 214 /// 215 void WalkAST::checkLoopConditionForFloat(const ForStmt *FS) { 216 if (!filter.check_FloatLoopCounter) 217 return; 218 219 // Does the loop have a condition? 220 const Expr *condition = FS->getCond(); 221 222 if (!condition) 223 return; 224 225 // Does the loop have an increment? 226 const Expr *increment = FS->getInc(); 227 228 if (!increment) 229 return; 230 231 // Strip away '()' and casts. 232 condition = condition->IgnoreParenCasts(); 233 increment = increment->IgnoreParenCasts(); 234 235 // Is the loop condition a comparison? 236 const BinaryOperator *B = dyn_cast<BinaryOperator>(condition); 237 238 if (!B) 239 return; 240 241 // Is this a comparison? 242 if (!(B->isRelationalOp() || B->isEqualityOp())) 243 return; 244 245 // Are we comparing variables? 246 const DeclRefExpr *drLHS = 247 dyn_cast<DeclRefExpr>(B->getLHS()->IgnoreParenLValueCasts()); 248 const DeclRefExpr *drRHS = 249 dyn_cast<DeclRefExpr>(B->getRHS()->IgnoreParenLValueCasts()); 250 251 // Does at least one of the variables have a floating point type? 252 drLHS = drLHS && drLHS->getType()->isRealFloatingType() ? drLHS : NULL; 253 drRHS = drRHS && drRHS->getType()->isRealFloatingType() ? drRHS : NULL; 254 255 if (!drLHS && !drRHS) 256 return; 257 258 const VarDecl *vdLHS = drLHS ? dyn_cast<VarDecl>(drLHS->getDecl()) : NULL; 259 const VarDecl *vdRHS = drRHS ? dyn_cast<VarDecl>(drRHS->getDecl()) : NULL; 260 261 if (!vdLHS && !vdRHS) 262 return; 263 264 // Does either variable appear in increment? 265 const DeclRefExpr *drInc = getIncrementedVar(increment, vdLHS, vdRHS); 266 267 if (!drInc) 268 return; 269 270 // Emit the error. First figure out which DeclRefExpr in the condition 271 // referenced the compared variable. 272 const DeclRefExpr *drCond = vdLHS == drInc->getDecl() ? drLHS : drRHS; 273 274 SmallVector<SourceRange, 2> ranges; 275 SmallString<256> sbuf; 276 llvm::raw_svector_ostream os(sbuf); 277 278 os << "Variable '" << drCond->getDecl()->getName() 279 << "' with floating point type '" << drCond->getType().getAsString() 280 << "' should not be used as a loop counter"; 281 282 ranges.push_back(drCond->getSourceRange()); 283 ranges.push_back(drInc->getSourceRange()); 284 285 const char *bugType = "Floating point variable used as loop counter"; 286 287 PathDiagnosticLocation FSLoc = 288 PathDiagnosticLocation::createBegin(FS, BR.getSourceManager(), AC); 289 BR.EmitBasicReport(AC->getDecl(), 290 bugType, "Security", os.str(), 291 FSLoc, ranges.data(), ranges.size()); 292 } 293 294 //===----------------------------------------------------------------------===// 295 // Check: Any use of 'gets' is insecure. 296 // Originally: <rdar://problem/6335715> 297 // Implements (part of): 300-BSI (buildsecurityin.us-cert.gov) 298 // CWE-242: Use of Inherently Dangerous Function 299 //===----------------------------------------------------------------------===// 300 301 void WalkAST::checkCall_gets(const CallExpr *CE, const FunctionDecl *FD) { 302 if (!filter.check_gets) 303 return; 304 305 const FunctionProtoType *FPT 306 = dyn_cast<FunctionProtoType>(FD->getType().IgnoreParens()); 307 if (!FPT) 308 return; 309 310 // Verify that the function takes a single argument. 311 if (FPT->getNumArgs() != 1) 312 return; 313 314 // Is the argument a 'char*'? 315 const PointerType *PT = dyn_cast<PointerType>(FPT->getArgType(0)); 316 if (!PT) 317 return; 318 319 if (PT->getPointeeType().getUnqualifiedType() != BR.getContext().CharTy) 320 return; 321 322 // Issue a warning. 323 SourceRange R = CE->getCallee()->getSourceRange(); 324 PathDiagnosticLocation CELoc = 325 PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC); 326 BR.EmitBasicReport(AC->getDecl(), 327 "Potential buffer overflow in call to 'gets'", 328 "Security", 329 "Call to function 'gets' is extremely insecure as it can " 330 "always result in a buffer overflow", 331 CELoc, &R, 1); 332 } 333 334 //===----------------------------------------------------------------------===// 335 // Check: Any use of 'getpwd' is insecure. 336 // CWE-477: Use of Obsolete Functions 337 //===----------------------------------------------------------------------===// 338 339 void WalkAST::checkCall_getpw(const CallExpr *CE, const FunctionDecl *FD) { 340 if (!filter.check_getpw) 341 return; 342 343 const FunctionProtoType *FPT 344 = dyn_cast<FunctionProtoType>(FD->getType().IgnoreParens()); 345 if (!FPT) 346 return; 347 348 // Verify that the function takes two arguments. 349 if (FPT->getNumArgs() != 2) 350 return; 351 352 // Verify the first argument type is integer. 353 if (!FPT->getArgType(0)->isIntegerType()) 354 return; 355 356 // Verify the second argument type is char*. 357 const PointerType *PT = dyn_cast<PointerType>(FPT->getArgType(1)); 358 if (!PT) 359 return; 360 361 if (PT->getPointeeType().getUnqualifiedType() != BR.getContext().CharTy) 362 return; 363 364 // Issue a warning. 365 SourceRange R = CE->getCallee()->getSourceRange(); 366 PathDiagnosticLocation CELoc = 367 PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC); 368 BR.EmitBasicReport(AC->getDecl(), 369 "Potential buffer overflow in call to 'getpw'", 370 "Security", 371 "The getpw() function is dangerous as it may overflow the " 372 "provided buffer. It is obsoleted by getpwuid().", 373 CELoc, &R, 1); 374 } 375 376 //===----------------------------------------------------------------------===// 377 // Check: Any use of 'mktemp' is insecure. It is obsoleted by mkstemp(). 378 // CWE-377: Insecure Temporary File 379 //===----------------------------------------------------------------------===// 380 381 void WalkAST::checkCall_mktemp(const CallExpr *CE, const FunctionDecl *FD) { 382 const FunctionProtoType *FPT 383 = dyn_cast<FunctionProtoType>(FD->getType().IgnoreParens()); 384 if(!FPT) 385 return; 386 387 // Verify that the function takes a single argument. 388 if (FPT->getNumArgs() != 1) 389 return; 390 391 // Verify that the argument is Pointer Type. 392 const PointerType *PT = dyn_cast<PointerType>(FPT->getArgType(0)); 393 if (!PT) 394 return; 395 396 // Verify that the argument is a 'char*'. 397 if (PT->getPointeeType().getUnqualifiedType() != BR.getContext().CharTy) 398 return; 399 400 // Issue a waring. 401 SourceRange R = CE->getCallee()->getSourceRange(); 402 PathDiagnosticLocation CELoc = 403 PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC); 404 BR.EmitBasicReport(AC->getDecl(), 405 "Potential insecure temporary file in call 'mktemp'", 406 "Security", 407 "Call to function 'mktemp' is insecure as it always " 408 "creates or uses insecure temporary file. Use 'mkstemp' " 409 "instead", 410 CELoc, &R, 1); 411 } 412 413 414 //===----------------------------------------------------------------------===// 415 // Check: Use of 'mkstemp', 'mktemp', 'mkdtemp' should contain at least 6 X's. 416 //===----------------------------------------------------------------------===// 417 418 void WalkAST::checkCall_mkstemp(const CallExpr *CE, const FunctionDecl *FD) { 419 if (!filter.check_mkstemp) 420 return; 421 422 StringRef Name = FD->getIdentifier()->getName(); 423 std::pair<signed, signed> ArgSuffix = 424 llvm::StringSwitch<std::pair<signed, signed> >(Name) 425 .Case("mktemp", std::make_pair(0,-1)) 426 .Case("mkstemp", std::make_pair(0,-1)) 427 .Case("mkdtemp", std::make_pair(0,-1)) 428 .Case("mkstemps", std::make_pair(0,1)) 429 .Default(std::make_pair(-1, -1)); 430 431 assert(ArgSuffix.first >= 0 && "Unsupported function"); 432 433 // Check if the number of arguments is consistent with out expectations. 434 unsigned numArgs = CE->getNumArgs(); 435 if ((signed) numArgs <= ArgSuffix.first) 436 return; 437 438 const StringLiteral *strArg = 439 dyn_cast<StringLiteral>(CE->getArg((unsigned)ArgSuffix.first) 440 ->IgnoreParenImpCasts()); 441 442 // Currently we only handle string literals. It is possible to do better, 443 // either by looking at references to const variables, or by doing real 444 // flow analysis. 445 if (!strArg || strArg->getCharByteWidth() != 1) 446 return; 447 448 // Count the number of X's, taking into account a possible cutoff suffix. 449 StringRef str = strArg->getString(); 450 unsigned numX = 0; 451 unsigned n = str.size(); 452 453 // Take into account the suffix. 454 unsigned suffix = 0; 455 if (ArgSuffix.second >= 0) { 456 const Expr *suffixEx = CE->getArg((unsigned)ArgSuffix.second); 457 llvm::APSInt Result; 458 if (!suffixEx->EvaluateAsInt(Result, BR.getContext())) 459 return; 460 // FIXME: Issue a warning. 461 if (Result.isNegative()) 462 return; 463 suffix = (unsigned) Result.getZExtValue(); 464 n = (n > suffix) ? n - suffix : 0; 465 } 466 467 for (unsigned i = 0; i < n; ++i) 468 if (str[i] == 'X') ++numX; 469 470 if (numX >= 6) 471 return; 472 473 // Issue a warning. 474 SourceRange R = strArg->getSourceRange(); 475 PathDiagnosticLocation CELoc = 476 PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC); 477 SmallString<512> buf; 478 llvm::raw_svector_ostream out(buf); 479 out << "Call to '" << Name << "' should have at least 6 'X's in the" 480 " format string to be secure (" << numX << " 'X'"; 481 if (numX != 1) 482 out << 's'; 483 out << " seen"; 484 if (suffix) { 485 out << ", " << suffix << " character"; 486 if (suffix > 1) 487 out << 's'; 488 out << " used as a suffix"; 489 } 490 out << ')'; 491 BR.EmitBasicReport(AC->getDecl(), 492 "Insecure temporary file creation", "Security", 493 out.str(), CELoc, &R, 1); 494 } 495 496 //===----------------------------------------------------------------------===// 497 // Check: Any use of 'strcpy' is insecure. 498 // 499 // CWE-119: Improper Restriction of Operations within 500 // the Bounds of a Memory Buffer 501 //===----------------------------------------------------------------------===// 502 void WalkAST::checkCall_strcpy(const CallExpr *CE, const FunctionDecl *FD) { 503 if (!filter.check_strcpy) 504 return; 505 506 if (!checkCall_strCommon(CE, FD)) 507 return; 508 509 // Issue a warning. 510 SourceRange R = CE->getCallee()->getSourceRange(); 511 PathDiagnosticLocation CELoc = 512 PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC); 513 BR.EmitBasicReport(AC->getDecl(), 514 "Potential insecure memory buffer bounds restriction in " 515 "call 'strcpy'", 516 "Security", 517 "Call to function 'strcpy' is insecure as it does not " 518 "provide bounding of the memory buffer. Replace " 519 "unbounded copy functions with analogous functions that " 520 "support length arguments such as 'strlcpy'. CWE-119.", 521 CELoc, &R, 1); 522 } 523 524 //===----------------------------------------------------------------------===// 525 // Check: Any use of 'strcat' is insecure. 526 // 527 // CWE-119: Improper Restriction of Operations within 528 // the Bounds of a Memory Buffer 529 //===----------------------------------------------------------------------===// 530 void WalkAST::checkCall_strcat(const CallExpr *CE, const FunctionDecl *FD) { 531 if (!filter.check_strcpy) 532 return; 533 534 if (!checkCall_strCommon(CE, FD)) 535 return; 536 537 // Issue a warning. 538 SourceRange R = CE->getCallee()->getSourceRange(); 539 PathDiagnosticLocation CELoc = 540 PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC); 541 BR.EmitBasicReport(AC->getDecl(), 542 "Potential insecure memory buffer bounds restriction in " 543 "call 'strcat'", 544 "Security", 545 "Call to function 'strcat' is insecure as it does not " 546 "provide bounding of the memory buffer. Replace " 547 "unbounded copy functions with analogous functions that " 548 "support length arguments such as 'strlcat'. CWE-119.", 549 CELoc, &R, 1); 550 } 551 552 //===----------------------------------------------------------------------===// 553 // Common check for str* functions with no bounds parameters. 554 //===----------------------------------------------------------------------===// 555 bool WalkAST::checkCall_strCommon(const CallExpr *CE, const FunctionDecl *FD) { 556 const FunctionProtoType *FPT 557 = dyn_cast<FunctionProtoType>(FD->getType().IgnoreParens()); 558 if (!FPT) 559 return false; 560 561 // Verify the function takes two arguments, three in the _chk version. 562 int numArgs = FPT->getNumArgs(); 563 if (numArgs != 2 && numArgs != 3) 564 return false; 565 566 // Verify the type for both arguments. 567 for (int i = 0; i < 2; i++) { 568 // Verify that the arguments are pointers. 569 const PointerType *PT = dyn_cast<PointerType>(FPT->getArgType(i)); 570 if (!PT) 571 return false; 572 573 // Verify that the argument is a 'char*'. 574 if (PT->getPointeeType().getUnqualifiedType() != BR.getContext().CharTy) 575 return false; 576 } 577 578 return true; 579 } 580 581 //===----------------------------------------------------------------------===// 582 // Check: Linear congruent random number generators should not be used 583 // Originally: <rdar://problem/63371000> 584 // CWE-338: Use of cryptographically weak prng 585 //===----------------------------------------------------------------------===// 586 587 void WalkAST::checkCall_rand(const CallExpr *CE, const FunctionDecl *FD) { 588 if (!filter.check_rand || !CheckRand) 589 return; 590 591 const FunctionProtoType *FTP 592 = dyn_cast<FunctionProtoType>(FD->getType().IgnoreParens()); 593 if (!FTP) 594 return; 595 596 if (FTP->getNumArgs() == 1) { 597 // Is the argument an 'unsigned short *'? 598 // (Actually any integer type is allowed.) 599 const PointerType *PT = dyn_cast<PointerType>(FTP->getArgType(0)); 600 if (!PT) 601 return; 602 603 if (! PT->getPointeeType()->isIntegerType()) 604 return; 605 } 606 else if (FTP->getNumArgs() != 0) 607 return; 608 609 // Issue a warning. 610 SmallString<256> buf1; 611 llvm::raw_svector_ostream os1(buf1); 612 os1 << '\'' << *FD << "' is a poor random number generator"; 613 614 SmallString<256> buf2; 615 llvm::raw_svector_ostream os2(buf2); 616 os2 << "Function '" << *FD 617 << "' is obsolete because it implements a poor random number generator." 618 << " Use 'arc4random' instead"; 619 620 SourceRange R = CE->getCallee()->getSourceRange(); 621 PathDiagnosticLocation CELoc = 622 PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC); 623 BR.EmitBasicReport(AC->getDecl(), os1.str(), "Security", os2.str(), 624 CELoc, &R, 1); 625 } 626 627 //===----------------------------------------------------------------------===// 628 // Check: 'random' should not be used 629 // Originally: <rdar://problem/63371000> 630 //===----------------------------------------------------------------------===// 631 632 void WalkAST::checkCall_random(const CallExpr *CE, const FunctionDecl *FD) { 633 if (!CheckRand || !filter.check_rand) 634 return; 635 636 const FunctionProtoType *FTP 637 = dyn_cast<FunctionProtoType>(FD->getType().IgnoreParens()); 638 if (!FTP) 639 return; 640 641 // Verify that the function takes no argument. 642 if (FTP->getNumArgs() != 0) 643 return; 644 645 // Issue a warning. 646 SourceRange R = CE->getCallee()->getSourceRange(); 647 PathDiagnosticLocation CELoc = 648 PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC); 649 BR.EmitBasicReport(AC->getDecl(), 650 "'random' is not a secure random number generator", 651 "Security", 652 "The 'random' function produces a sequence of values that " 653 "an adversary may be able to predict. Use 'arc4random' " 654 "instead", CELoc, &R, 1); 655 } 656 657 //===----------------------------------------------------------------------===// 658 // Check: 'vfork' should not be used. 659 // POS33-C: Do not use vfork(). 660 //===----------------------------------------------------------------------===// 661 662 void WalkAST::checkCall_vfork(const CallExpr *CE, const FunctionDecl *FD) { 663 if (!filter.check_vfork) 664 return; 665 666 // All calls to vfork() are insecure, issue a warning. 667 SourceRange R = CE->getCallee()->getSourceRange(); 668 PathDiagnosticLocation CELoc = 669 PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC); 670 BR.EmitBasicReport(AC->getDecl(), 671 "Potential insecure implementation-specific behavior in " 672 "call 'vfork'", 673 "Security", 674 "Call to function 'vfork' is insecure as it can lead to " 675 "denial of service situations in the parent process. " 676 "Replace calls to vfork with calls to the safer " 677 "'posix_spawn' function", 678 CELoc, &R, 1); 679 } 680 681 //===----------------------------------------------------------------------===// 682 // Check: Should check whether privileges are dropped successfully. 683 // Originally: <rdar://problem/6337132> 684 //===----------------------------------------------------------------------===// 685 686 void WalkAST::checkUncheckedReturnValue(CallExpr *CE) { 687 if (!filter.check_UncheckedReturn) 688 return; 689 690 const FunctionDecl *FD = CE->getDirectCallee(); 691 if (!FD) 692 return; 693 694 if (II_setid[0] == NULL) { 695 static const char * const identifiers[num_setids] = { 696 "setuid", "setgid", "seteuid", "setegid", 697 "setreuid", "setregid" 698 }; 699 700 for (size_t i = 0; i < num_setids; i++) 701 II_setid[i] = &BR.getContext().Idents.get(identifiers[i]); 702 } 703 704 const IdentifierInfo *id = FD->getIdentifier(); 705 size_t identifierid; 706 707 for (identifierid = 0; identifierid < num_setids; identifierid++) 708 if (id == II_setid[identifierid]) 709 break; 710 711 if (identifierid >= num_setids) 712 return; 713 714 const FunctionProtoType *FTP 715 = dyn_cast<FunctionProtoType>(FD->getType().IgnoreParens()); 716 if (!FTP) 717 return; 718 719 // Verify that the function takes one or two arguments (depending on 720 // the function). 721 if (FTP->getNumArgs() != (identifierid < 4 ? 1 : 2)) 722 return; 723 724 // The arguments must be integers. 725 for (unsigned i = 0; i < FTP->getNumArgs(); i++) 726 if (! FTP->getArgType(i)->isIntegerType()) 727 return; 728 729 // Issue a warning. 730 SmallString<256> buf1; 731 llvm::raw_svector_ostream os1(buf1); 732 os1 << "Return value is not checked in call to '" << *FD << '\''; 733 734 SmallString<256> buf2; 735 llvm::raw_svector_ostream os2(buf2); 736 os2 << "The return value from the call to '" << *FD 737 << "' is not checked. If an error occurs in '" << *FD 738 << "', the following code may execute with unexpected privileges"; 739 740 SourceRange R = CE->getCallee()->getSourceRange(); 741 PathDiagnosticLocation CELoc = 742 PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC); 743 BR.EmitBasicReport(AC->getDecl(), os1.str(), "Security", os2.str(), 744 CELoc, &R, 1); 745 } 746 747 //===----------------------------------------------------------------------===// 748 // SecuritySyntaxChecker 749 //===----------------------------------------------------------------------===// 750 751 namespace { 752 class SecuritySyntaxChecker : public Checker<check::ASTCodeBody> { 753 public: 754 ChecksFilter filter; 755 756 void checkASTCodeBody(const Decl *D, AnalysisManager& mgr, 757 BugReporter &BR) const { 758 WalkAST walker(BR, mgr.getAnalysisDeclContext(D), filter); 759 walker.Visit(D->getBody()); 760 } 761 }; 762 } 763 764 #define REGISTER_CHECKER(name) \ 765 namespace { class Checker_##name : public SecuritySyntaxChecker {}; }\ 766 void ento::register##name(CheckerManager &mgr) {\ 767 mgr.registerChecker<Checker_##name>()->filter.check_##name = true;\ 768 } 769 770 REGISTER_CHECKER(gets) 771 REGISTER_CHECKER(getpw) 772 REGISTER_CHECKER(mkstemp) 773 REGISTER_CHECKER(mktemp) 774 REGISTER_CHECKER(strcpy) 775 REGISTER_CHECKER(rand) 776 REGISTER_CHECKER(vfork) 777 REGISTER_CHECKER(FloatLoopCounter) 778 REGISTER_CHECKER(UncheckedReturn) 779 780 781