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