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