VforkChecker.cpp 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  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. #include <optional>
  38. using namespace clang;
  39. using namespace ento;
  40. namespace {
  41. class VforkChecker : public Checker<check::PreCall, check::PostCall,
  42. check::Bind, check::PreStmt<ReturnStmt>> {
  43. mutable std::unique_ptr<BuiltinBug> BT;
  44. mutable llvm::SmallSet<const IdentifierInfo *, 10> VforkAllowlist;
  45. mutable const IdentifierInfo *II_vfork;
  46. static bool isChildProcess(const ProgramStateRef State);
  47. bool isVforkCall(const Decl *D, CheckerContext &C) const;
  48. bool isCallExplicitelyAllowed(const IdentifierInfo *II,
  49. CheckerContext &C) const;
  50. void reportBug(const char *What, CheckerContext &C,
  51. const char *Details = nullptr) const;
  52. public:
  53. VforkChecker() : II_vfork(nullptr) {}
  54. void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
  55. void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
  56. void checkBind(SVal L, SVal V, const Stmt *S, CheckerContext &C) const;
  57. void checkPreStmt(const ReturnStmt *RS, CheckerContext &C) const;
  58. };
  59. } // end anonymous namespace
  60. // This trait holds region of variable that is assigned with vfork's
  61. // return value (this is the only region child is allowed to write).
  62. // VFORK_RESULT_INVALID means that we are in parent process.
  63. // VFORK_RESULT_NONE means that vfork's return value hasn't been assigned.
  64. // Other values point to valid regions.
  65. REGISTER_TRAIT_WITH_PROGRAMSTATE(VforkResultRegion, const void *)
  66. #define VFORK_RESULT_INVALID 0
  67. #define VFORK_RESULT_NONE ((void *)(uintptr_t)1)
  68. bool VforkChecker::isChildProcess(const ProgramStateRef State) {
  69. return State->get<VforkResultRegion>() != VFORK_RESULT_INVALID;
  70. }
  71. bool VforkChecker::isVforkCall(const Decl *D, CheckerContext &C) const {
  72. auto FD = dyn_cast_or_null<FunctionDecl>(D);
  73. if (!FD || !C.isCLibraryFunction(FD))
  74. return false;
  75. if (!II_vfork) {
  76. ASTContext &AC = C.getASTContext();
  77. II_vfork = &AC.Idents.get("vfork");
  78. }
  79. return FD->getIdentifier() == II_vfork;
  80. }
  81. // Returns true iff ok to call function after successful vfork.
  82. bool VforkChecker::isCallExplicitelyAllowed(const IdentifierInfo *II,
  83. CheckerContext &C) const {
  84. if (VforkAllowlist.empty()) {
  85. // According to manpage.
  86. const char *ids[] = {
  87. "_Exit",
  88. "_exit",
  89. "execl",
  90. "execle",
  91. "execlp",
  92. "execv",
  93. "execve",
  94. "execvp",
  95. "execvpe",
  96. nullptr
  97. };
  98. ASTContext &AC = C.getASTContext();
  99. for (const char **id = ids; *id; ++id)
  100. VforkAllowlist.insert(&AC.Idents.get(*id));
  101. }
  102. return VforkAllowlist.count(II);
  103. }
  104. void VforkChecker::reportBug(const char *What, CheckerContext &C,
  105. const char *Details) const {
  106. if (ExplodedNode *N = C.generateErrorNode(C.getState())) {
  107. if (!BT)
  108. BT.reset(new BuiltinBug(this,
  109. "Dangerous construct in a vforked process"));
  110. SmallString<256> buf;
  111. llvm::raw_svector_ostream os(buf);
  112. os << What << " is prohibited after a successful vfork";
  113. if (Details)
  114. os << "; " << Details;
  115. auto Report = std::make_unique<PathSensitiveBugReport>(*BT, os.str(), N);
  116. // TODO: mark vfork call in BugReportVisitor
  117. C.emitReport(std::move(Report));
  118. }
  119. }
  120. // Detect calls to vfork and split execution appropriately.
  121. void VforkChecker::checkPostCall(const CallEvent &Call,
  122. CheckerContext &C) const {
  123. // We can't call vfork in child so don't bother
  124. // (corresponding warning has already been emitted in checkPreCall).
  125. ProgramStateRef State = C.getState();
  126. if (isChildProcess(State))
  127. return;
  128. if (!isVforkCall(Call.getDecl(), C))
  129. return;
  130. // Get return value of vfork.
  131. SVal VforkRetVal = Call.getReturnValue();
  132. std::optional<DefinedOrUnknownSVal> DVal =
  133. VforkRetVal.getAs<DefinedOrUnknownSVal>();
  134. if (!DVal)
  135. return;
  136. // Get assigned variable.
  137. const ParentMap &PM = C.getLocationContext()->getParentMap();
  138. const Stmt *P = PM.getParentIgnoreParenCasts(Call.getOriginExpr());
  139. const VarDecl *LhsDecl;
  140. std::tie(LhsDecl, std::ignore) = parseAssignment(P);
  141. // Get assigned memory region.
  142. MemRegionManager &M = C.getStoreManager().getRegionManager();
  143. const MemRegion *LhsDeclReg =
  144. LhsDecl
  145. ? M.getVarRegion(LhsDecl, C.getLocationContext())
  146. : (const MemRegion *)VFORK_RESULT_NONE;
  147. // Parent branch gets nonzero return value (according to manpage).
  148. ProgramStateRef ParentState, ChildState;
  149. std::tie(ParentState, ChildState) = C.getState()->assume(*DVal);
  150. C.addTransition(ParentState);
  151. ChildState = ChildState->set<VforkResultRegion>(LhsDeclReg);
  152. C.addTransition(ChildState);
  153. }
  154. // Prohibit calls to functions in child process which are not explicitly
  155. // allowed.
  156. void VforkChecker::checkPreCall(const CallEvent &Call,
  157. CheckerContext &C) const {
  158. ProgramStateRef State = C.getState();
  159. if (isChildProcess(State) &&
  160. !isCallExplicitelyAllowed(Call.getCalleeIdentifier(), C))
  161. reportBug("This function call", C);
  162. }
  163. // Prohibit writes in child process (except for vfork's lhs).
  164. void VforkChecker::checkBind(SVal L, SVal V, const Stmt *S,
  165. CheckerContext &C) const {
  166. ProgramStateRef State = C.getState();
  167. if (!isChildProcess(State))
  168. return;
  169. const MemRegion *VforkLhs =
  170. static_cast<const MemRegion *>(State->get<VforkResultRegion>());
  171. const MemRegion *MR = L.getAsRegion();
  172. // Child is allowed to modify only vfork's lhs.
  173. if (!MR || MR == VforkLhs)
  174. return;
  175. reportBug("This assignment", C);
  176. }
  177. // Prohibit return from function in child process.
  178. void VforkChecker::checkPreStmt(const ReturnStmt *RS, CheckerContext &C) const {
  179. ProgramStateRef State = C.getState();
  180. if (isChildProcess(State))
  181. reportBug("Return", C, "call _exit() instead");
  182. }
  183. void ento::registerVforkChecker(CheckerManager &mgr) {
  184. mgr.registerChecker<VforkChecker>();
  185. }
  186. bool ento::shouldRegisterVforkChecker(const CheckerManager &mgr) {
  187. return true;
  188. }