VforkChecker.cpp 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. //===- VforkChecker.cpp -------- Vfork usage checks --------------*- C++ -*-==//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file defines vfork checker which checks for dangerous uses of vfork.
  10. // Vforked process shares memory (including stack) with parent so it's
  11. // range of actions is significantly limited: can't write variables,
  12. // can't call functions not in the allowed list, etc. For more details, see
  13. // http://man7.org/linux/man-pages/man2/vfork.2.html
  14. //
  15. // This checker checks for prohibited constructs in vforked process.
  16. // The state transition diagram:
  17. // PARENT ---(vfork() == 0)--> CHILD
  18. // |
  19. // --(*p = ...)--> bug
  20. // |
  21. // --foo()--> bug
  22. // |
  23. // --return--> bug
  24. //
  25. //===----------------------------------------------------------------------===//
  26. #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
  27. #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
  28. #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
  29. #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h"
  30. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
  31. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
  32. #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
  33. #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
  34. #include "clang/StaticAnalyzer/Core/Checker.h"
  35. #include "clang/StaticAnalyzer/Core/CheckerManager.h"
  36. #include "clang/AST/ParentMap.h"
  37. using namespace clang;
  38. using namespace ento;
  39. namespace {
  40. class VforkChecker : public Checker<check::PreCall, check::PostCall,
  41. check::Bind, check::PreStmt<ReturnStmt>> {
  42. mutable std::unique_ptr<BuiltinBug> BT;
  43. mutable llvm::SmallSet<const IdentifierInfo *, 10> VforkAllowlist;
  44. mutable const IdentifierInfo *II_vfork;
  45. static bool isChildProcess(const ProgramStateRef State);
  46. bool isVforkCall(const Decl *D, CheckerContext &C) const;
  47. bool isCallExplicitelyAllowed(const IdentifierInfo *II,
  48. CheckerContext &C) const;
  49. void reportBug(const char *What, CheckerContext &C,
  50. const char *Details = nullptr) const;
  51. public:
  52. VforkChecker() : II_vfork(nullptr) {}
  53. void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
  54. void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
  55. void checkBind(SVal L, SVal V, const Stmt *S, CheckerContext &C) const;
  56. void checkPreStmt(const ReturnStmt *RS, CheckerContext &C) const;
  57. };
  58. } // end anonymous namespace
  59. // This trait holds region of variable that is assigned with vfork's
  60. // return value (this is the only region child is allowed to write).
  61. // VFORK_RESULT_INVALID means that we are in parent process.
  62. // VFORK_RESULT_NONE means that vfork's return value hasn't been assigned.
  63. // Other values point to valid regions.
  64. REGISTER_TRAIT_WITH_PROGRAMSTATE(VforkResultRegion, const void *)
  65. #define VFORK_RESULT_INVALID 0
  66. #define VFORK_RESULT_NONE ((void *)(uintptr_t)1)
  67. bool VforkChecker::isChildProcess(const ProgramStateRef State) {
  68. return State->get<VforkResultRegion>() != VFORK_RESULT_INVALID;
  69. }
  70. bool VforkChecker::isVforkCall(const Decl *D, CheckerContext &C) const {
  71. auto FD = dyn_cast_or_null<FunctionDecl>(D);
  72. if (!FD || !C.isCLibraryFunction(FD))
  73. return false;
  74. if (!II_vfork) {
  75. ASTContext &AC = C.getASTContext();
  76. II_vfork = &AC.Idents.get("vfork");
  77. }
  78. return FD->getIdentifier() == II_vfork;
  79. }
  80. // Returns true iff ok to call function after successful vfork.
  81. bool VforkChecker::isCallExplicitelyAllowed(const IdentifierInfo *II,
  82. CheckerContext &C) const {
  83. if (VforkAllowlist.empty()) {
  84. // According to manpage.
  85. const char *ids[] = {
  86. "_Exit",
  87. "_exit",
  88. "execl",
  89. "execle",
  90. "execlp",
  91. "execv",
  92. "execve",
  93. "execvp",
  94. "execvpe",
  95. nullptr
  96. };
  97. ASTContext &AC = C.getASTContext();
  98. for (const char **id = ids; *id; ++id)
  99. VforkAllowlist.insert(&AC.Idents.get(*id));
  100. }
  101. return VforkAllowlist.count(II);
  102. }
  103. void VforkChecker::reportBug(const char *What, CheckerContext &C,
  104. const char *Details) const {
  105. if (ExplodedNode *N = C.generateErrorNode(C.getState())) {
  106. if (!BT)
  107. BT.reset(new BuiltinBug(this,
  108. "Dangerous construct in a vforked process"));
  109. SmallString<256> buf;
  110. llvm::raw_svector_ostream os(buf);
  111. os << What << " is prohibited after a successful vfork";
  112. if (Details)
  113. os << "; " << Details;
  114. auto Report = std::make_unique<PathSensitiveBugReport>(*BT, os.str(), N);
  115. // TODO: mark vfork call in BugReportVisitor
  116. C.emitReport(std::move(Report));
  117. }
  118. }
  119. // Detect calls to vfork and split execution appropriately.
  120. void VforkChecker::checkPostCall(const CallEvent &Call,
  121. CheckerContext &C) const {
  122. // We can't call vfork in child so don't bother
  123. // (corresponding warning has already been emitted in checkPreCall).
  124. ProgramStateRef State = C.getState();
  125. if (isChildProcess(State))
  126. return;
  127. if (!isVforkCall(Call.getDecl(), C))
  128. return;
  129. // Get return value of vfork.
  130. SVal VforkRetVal = Call.getReturnValue();
  131. Optional<DefinedOrUnknownSVal> DVal =
  132. VforkRetVal.getAs<DefinedOrUnknownSVal>();
  133. if (!DVal)
  134. return;
  135. // Get assigned variable.
  136. const ParentMap &PM = C.getLocationContext()->getParentMap();
  137. const Stmt *P = PM.getParentIgnoreParenCasts(Call.getOriginExpr());
  138. const VarDecl *LhsDecl;
  139. std::tie(LhsDecl, std::ignore) = parseAssignment(P);
  140. // Get assigned memory region.
  141. MemRegionManager &M = C.getStoreManager().getRegionManager();
  142. const MemRegion *LhsDeclReg =
  143. LhsDecl
  144. ? M.getVarRegion(LhsDecl, C.getLocationContext())
  145. : (const MemRegion *)VFORK_RESULT_NONE;
  146. // Parent branch gets nonzero return value (according to manpage).
  147. ProgramStateRef ParentState, ChildState;
  148. std::tie(ParentState, ChildState) = C.getState()->assume(*DVal);
  149. C.addTransition(ParentState);
  150. ChildState = ChildState->set<VforkResultRegion>(LhsDeclReg);
  151. C.addTransition(ChildState);
  152. }
  153. // Prohibit calls to functions in child process which are not explicitly
  154. // allowed.
  155. void VforkChecker::checkPreCall(const CallEvent &Call,
  156. CheckerContext &C) const {
  157. ProgramStateRef State = C.getState();
  158. if (isChildProcess(State) &&
  159. !isCallExplicitelyAllowed(Call.getCalleeIdentifier(), C))
  160. reportBug("This function call", C);
  161. }
  162. // Prohibit writes in child process (except for vfork's lhs).
  163. void VforkChecker::checkBind(SVal L, SVal V, const Stmt *S,
  164. CheckerContext &C) const {
  165. ProgramStateRef State = C.getState();
  166. if (!isChildProcess(State))
  167. return;
  168. const MemRegion *VforkLhs =
  169. static_cast<const MemRegion *>(State->get<VforkResultRegion>());
  170. const MemRegion *MR = L.getAsRegion();
  171. // Child is allowed to modify only vfork's lhs.
  172. if (!MR || MR == VforkLhs)
  173. return;
  174. reportBug("This assignment", C);
  175. }
  176. // Prohibit return from function in child process.
  177. void VforkChecker::checkPreStmt(const ReturnStmt *RS, CheckerContext &C) const {
  178. ProgramStateRef State = C.getState();
  179. if (isChildProcess(State))
  180. reportBug("Return", C, "call _exit() instead");
  181. }
  182. void ento::registerVforkChecker(CheckerManager &mgr) {
  183. mgr.registerChecker<VforkChecker>();
  184. }
  185. bool ento::shouldRegisterVforkChecker(const CheckerManager &mgr) {
  186. return true;
  187. }