clang  15.0.0git
VforkChecker.cpp
Go to the documentation of this file.
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 
37 #include "clang/AST/ParentMap.h"
38 
39 using namespace clang;
40 using namespace ento;
41 
42 namespace {
43 
44 class VforkChecker : public Checker<check::PreCall, check::PostCall,
45  check::Bind, check::PreStmt<ReturnStmt>> {
46  mutable std::unique_ptr<BuiltinBug> BT;
47  mutable llvm::SmallSet<const IdentifierInfo *, 10> VforkAllowlist;
48  mutable const IdentifierInfo *II_vfork;
49 
50  static bool isChildProcess(const ProgramStateRef State);
51 
52  bool isVforkCall(const Decl *D, CheckerContext &C) const;
53  bool isCallExplicitelyAllowed(const IdentifierInfo *II,
54  CheckerContext &C) const;
55 
56  void reportBug(const char *What, CheckerContext &C,
57  const char *Details = nullptr) const;
58 
59 public:
60  VforkChecker() : II_vfork(nullptr) {}
61 
62  void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
63  void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
64  void checkBind(SVal L, SVal V, const Stmt *S, CheckerContext &C) const;
65  void checkPreStmt(const ReturnStmt *RS, CheckerContext &C) const;
66 };
67 
68 } // end anonymous namespace
69 
70 // This trait holds region of variable that is assigned with vfork's
71 // return value (this is the only region child is allowed to write).
72 // VFORK_RESULT_INVALID means that we are in parent process.
73 // VFORK_RESULT_NONE means that vfork's return value hasn't been assigned.
74 // Other values point to valid regions.
75 REGISTER_TRAIT_WITH_PROGRAMSTATE(VforkResultRegion, const void *)
76 #define VFORK_RESULT_INVALID 0
77 #define VFORK_RESULT_NONE ((void *)(uintptr_t)1)
78 
79 bool VforkChecker::isChildProcess(const ProgramStateRef State) {
80  return State->get<VforkResultRegion>() != VFORK_RESULT_INVALID;
81 }
82 
83 bool VforkChecker::isVforkCall(const Decl *D, CheckerContext &C) const {
84  auto FD = dyn_cast_or_null<FunctionDecl>(D);
85  if (!FD || !C.isCLibraryFunction(FD))
86  return false;
87 
88  if (!II_vfork) {
89  ASTContext &AC = C.getASTContext();
90  II_vfork = &AC.Idents.get("vfork");
91  }
92 
93  return FD->getIdentifier() == II_vfork;
94 }
95 
96 // Returns true iff ok to call function after successful vfork.
97 bool VforkChecker::isCallExplicitelyAllowed(const IdentifierInfo *II,
98  CheckerContext &C) const {
99  if (VforkAllowlist.empty()) {
100  // According to manpage.
101  const char *ids[] = {
102  "_Exit",
103  "_exit",
104  "execl",
105  "execle",
106  "execlp",
107  "execv",
108  "execve",
109  "execvp",
110  "execvpe",
111  nullptr
112  };
113 
114  ASTContext &AC = C.getASTContext();
115  for (const char **id = ids; *id; ++id)
116  VforkAllowlist.insert(&AC.Idents.get(*id));
117  }
118 
119  return VforkAllowlist.count(II);
120 }
121 
122 void VforkChecker::reportBug(const char *What, CheckerContext &C,
123  const char *Details) const {
124  if (ExplodedNode *N = C.generateErrorNode(C.getState())) {
125  if (!BT)
126  BT.reset(new BuiltinBug(this,
127  "Dangerous construct in a vforked process"));
128 
129  SmallString<256> buf;
130  llvm::raw_svector_ostream os(buf);
131 
132  os << What << " is prohibited after a successful vfork";
133 
134  if (Details)
135  os << "; " << Details;
136 
137  auto Report = std::make_unique<PathSensitiveBugReport>(*BT, os.str(), N);
138  // TODO: mark vfork call in BugReportVisitor
139  C.emitReport(std::move(Report));
140  }
141 }
142 
143 // Detect calls to vfork and split execution appropriately.
144 void VforkChecker::checkPostCall(const CallEvent &Call,
145  CheckerContext &C) const {
146  // We can't call vfork in child so don't bother
147  // (corresponding warning has already been emitted in checkPreCall).
148  ProgramStateRef State = C.getState();
149  if (isChildProcess(State))
150  return;
151 
152  if (!isVforkCall(Call.getDecl(), C))
153  return;
154 
155  // Get return value of vfork.
156  SVal VforkRetVal = Call.getReturnValue();
158  VforkRetVal.getAs<DefinedOrUnknownSVal>();
159  if (!DVal)
160  return;
161 
162  // Get assigned variable.
163  const ParentMap &PM = C.getLocationContext()->getParentMap();
164  const Stmt *P = PM.getParentIgnoreParenCasts(Call.getOriginExpr());
165  const VarDecl *LhsDecl;
166  std::tie(LhsDecl, std::ignore) = parseAssignment(P);
167 
168  // Get assigned memory region.
169  MemRegionManager &M = C.getStoreManager().getRegionManager();
170  const MemRegion *LhsDeclReg =
171  LhsDecl
172  ? M.getVarRegion(LhsDecl, C.getLocationContext())
173  : (const MemRegion *)VFORK_RESULT_NONE;
174 
175  // Parent branch gets nonzero return value (according to manpage).
176  ProgramStateRef ParentState, ChildState;
177  std::tie(ParentState, ChildState) = C.getState()->assume(*DVal);
178  C.addTransition(ParentState);
179  ChildState = ChildState->set<VforkResultRegion>(LhsDeclReg);
180  C.addTransition(ChildState);
181 }
182 
183 // Prohibit calls to functions in child process which are not explicitly
184 // allowed.
185 void VforkChecker::checkPreCall(const CallEvent &Call,
186  CheckerContext &C) const {
187  ProgramStateRef State = C.getState();
188  if (isChildProcess(State) &&
189  !isCallExplicitelyAllowed(Call.getCalleeIdentifier(), C))
190  reportBug("This function call", C);
191 }
192 
193 // Prohibit writes in child process (except for vfork's lhs).
194 void VforkChecker::checkBind(SVal L, SVal V, const Stmt *S,
195  CheckerContext &C) const {
196  ProgramStateRef State = C.getState();
197  if (!isChildProcess(State))
198  return;
199 
200  const MemRegion *VforkLhs =
201  static_cast<const MemRegion *>(State->get<VforkResultRegion>());
202  const MemRegion *MR = L.getAsRegion();
203 
204  // Child is allowed to modify only vfork's lhs.
205  if (!MR || MR == VforkLhs)
206  return;
207 
208  reportBug("This assignment", C);
209 }
210 
211 // Prohibit return from function in child process.
212 void VforkChecker::checkPreStmt(const ReturnStmt *RS, CheckerContext &C) const {
213  ProgramStateRef State = C.getState();
214  if (isChildProcess(State))
215  reportBug("Return", C, "call _exit() instead");
216 }
217 
218 void ento::registerVforkChecker(CheckerManager &mgr) {
219  mgr.registerChecker<VforkChecker>();
220 }
221 
222 bool ento::shouldRegisterVforkChecker(const CheckerManager &mgr) {
223  return true;
224 }
clang::IdentifierTable::get
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
Definition: IdentifierTable.h:596
clang::ParentMap::getParentIgnoreParenCasts
Stmt * getParentIgnoreParenCasts(Stmt *) const
Definition: ParentMap.cpp:144
clang::ento::ProgramStateRef
IntrusiveRefCntPtr< const ProgramState > ProgramStateRef
Definition: ProgramState_Fwd.h:37
AttributeLangSupport::C
@ C
Definition: SemaDeclAttr.cpp:55
SymbolManager.h
llvm::Optional
Definition: LLVM.h:40
clang::index::SymbolRole::Call
@ Call
VFORK_RESULT_INVALID
#define VFORK_RESULT_INVALID
Definition: VforkChecker.cpp:76
REGISTER_TRAIT_WITH_PROGRAMSTATE
#define REGISTER_TRAIT_WITH_PROGRAMSTATE(Name, Type)
Declares a program state trait for type Type called Name, and introduce a type named NameTy.
Definition: ProgramStateTrait.h:34
CallEvent.h
clang::ento::parseAssignment
std::pair< const clang::VarDecl *, const clang::Expr * > parseAssignment(const Stmt *S)
Definition: CheckerHelpers.cpp:81
V
#define V(N, I)
Definition: ASTContext.h:3176
BuiltinCheckerRegistration.h
CheckerManager.h
clang::ASTContext
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:208
llvm::SmallString
Definition: LLVM.h:37
clang::VarDecl
Represents a variable declaration or definition.
Definition: Decl.h:874
clang::ParentMap
Definition: ParentMap.h:20
VFORK_RESULT_NONE
#define VFORK_RESULT_NONE
Definition: VforkChecker.cpp:77
P
StringRef P
Definition: ASTMatchersInternal.cpp:563
BugType.h
clang::ASTContext::Idents
IdentifierTable & Idents
Definition: ASTContext.h:655
clang::Decl
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:83
State
LineState State
Definition: UnwrappedLineFormatter.cpp:1126
clang::IdentifierInfo
One of these records is kept for each identifier that is lexed.
Definition: IdentifierTable.h:84
CheckerContext.h
ProgramState.h
Checker.h
ParentMap.h
clang
Definition: CalledOnceCheck.h:17
clang::Stmt
Stmt - This represents one statement.
Definition: Stmt.h:69
CheckerHelpers.h
ProgramStateTrait.h
clang::ReturnStmt
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition: Stmt.h:2764