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 whitelist, 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 
27 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
28 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
29 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
30 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h"
31 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
32 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
33 #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
34 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
35 #include "clang/StaticAnalyzer/Core/Checker.h"
36 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
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> VforkWhitelist;
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 isCallWhitelisted(const IdentifierInfo *II, CheckerContext &C) const;
54 
55   void reportBug(const char *What, CheckerContext &C,
56                  const char *Details = nullptr) const;
57 
58 public:
59   VforkChecker() : II_vfork(nullptr) {}
60 
61   void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
62   void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
63   void checkBind(SVal L, SVal V, const Stmt *S, CheckerContext &C) const;
64   void checkPreStmt(const ReturnStmt *RS, CheckerContext &C) const;
65 };
66 
67 } // end anonymous namespace
68 
69 // This trait holds region of variable that is assigned with vfork's
70 // return value (this is the only region child is allowed to write).
71 // VFORK_RESULT_INVALID means that we are in parent process.
72 // VFORK_RESULT_NONE means that vfork's return value hasn't been assigned.
73 // Other values point to valid regions.
74 REGISTER_TRAIT_WITH_PROGRAMSTATE(VforkResultRegion, const void *)
75 #define VFORK_RESULT_INVALID 0
76 #define VFORK_RESULT_NONE ((void *)(uintptr_t)1)
77 
78 bool VforkChecker::isChildProcess(const ProgramStateRef State) {
79   return State->get<VforkResultRegion>() != VFORK_RESULT_INVALID;
80 }
81 
82 bool VforkChecker::isVforkCall(const Decl *D, CheckerContext &C) const {
83   auto FD = dyn_cast_or_null<FunctionDecl>(D);
84   if (!FD || !C.isCLibraryFunction(FD))
85     return false;
86 
87   if (!II_vfork) {
88     ASTContext &AC = C.getASTContext();
89     II_vfork = &AC.Idents.get("vfork");
90   }
91 
92   return FD->getIdentifier() == II_vfork;
93 }
94 
95 // Returns true iff ok to call function after successful vfork.
96 bool VforkChecker::isCallWhitelisted(const IdentifierInfo *II,
97                                  CheckerContext &C) const {
98   if (VforkWhitelist.empty()) {
99     // According to manpage.
100     const char *ids[] = {
101       "_exit",
102       "_Exit",
103       "execl",
104       "execlp",
105       "execle",
106       "execv",
107       "execvp",
108       "execvpe",
109       nullptr
110     };
111 
112     ASTContext &AC = C.getASTContext();
113     for (const char **id = ids; *id; ++id)
114       VforkWhitelist.insert(&AC.Idents.get(*id));
115   }
116 
117   return VforkWhitelist.count(II);
118 }
119 
120 void VforkChecker::reportBug(const char *What, CheckerContext &C,
121                              const char *Details) const {
122   if (ExplodedNode *N = C.generateErrorNode(C.getState())) {
123     if (!BT)
124       BT.reset(new BuiltinBug(this,
125                               "Dangerous construct in a vforked process"));
126 
127     SmallString<256> buf;
128     llvm::raw_svector_ostream os(buf);
129 
130     os << What << " is prohibited after a successful vfork";
131 
132     if (Details)
133       os << "; " << Details;
134 
135     auto Report = std::make_unique<PathSensitiveBugReport>(*BT, os.str(), N);
136     // TODO: mark vfork call in BugReportVisitor
137     C.emitReport(std::move(Report));
138   }
139 }
140 
141 // Detect calls to vfork and split execution appropriately.
142 void VforkChecker::checkPostCall(const CallEvent &Call,
143                                  CheckerContext &C) const {
144   // We can't call vfork in child so don't bother
145   // (corresponding warning has already been emitted in checkPreCall).
146   ProgramStateRef State = C.getState();
147   if (isChildProcess(State))
148     return;
149 
150   if (!isVforkCall(Call.getDecl(), C))
151     return;
152 
153   // Get return value of vfork.
154   SVal VforkRetVal = Call.getReturnValue();
155   Optional<DefinedOrUnknownSVal> DVal =
156     VforkRetVal.getAs<DefinedOrUnknownSVal>();
157   if (!DVal)
158     return;
159 
160   // Get assigned variable.
161   const ParentMap &PM = C.getLocationContext()->getParentMap();
162   const Stmt *P = PM.getParentIgnoreParenCasts(Call.getOriginExpr());
163   const VarDecl *LhsDecl;
164   std::tie(LhsDecl, std::ignore) = parseAssignment(P);
165 
166   // Get assigned memory region.
167   MemRegionManager &M = C.getStoreManager().getRegionManager();
168   const MemRegion *LhsDeclReg =
169     LhsDecl
170       ? M.getVarRegion(LhsDecl, C.getLocationContext())
171       : (const MemRegion *)VFORK_RESULT_NONE;
172 
173   // Parent branch gets nonzero return value (according to manpage).
174   ProgramStateRef ParentState, ChildState;
175   std::tie(ParentState, ChildState) = C.getState()->assume(*DVal);
176   C.addTransition(ParentState);
177   ChildState = ChildState->set<VforkResultRegion>(LhsDeclReg);
178   C.addTransition(ChildState);
179 }
180 
181 // Prohibit calls to non-whitelist functions in child process.
182 void VforkChecker::checkPreCall(const CallEvent &Call,
183                                 CheckerContext &C) const {
184   ProgramStateRef State = C.getState();
185   if (isChildProcess(State)
186       && !isCallWhitelisted(Call.getCalleeIdentifier(), C))
187     reportBug("This function call", C);
188 }
189 
190 // Prohibit writes in child process (except for vfork's lhs).
191 void VforkChecker::checkBind(SVal L, SVal V, const Stmt *S,
192                              CheckerContext &C) const {
193   ProgramStateRef State = C.getState();
194   if (!isChildProcess(State))
195     return;
196 
197   const MemRegion *VforkLhs =
198     static_cast<const MemRegion *>(State->get<VforkResultRegion>());
199   const MemRegion *MR = L.getAsRegion();
200 
201   // Child is allowed to modify only vfork's lhs.
202   if (!MR || MR == VforkLhs)
203     return;
204 
205   reportBug("This assignment", C);
206 }
207 
208 // Prohibit return from function in child process.
209 void VforkChecker::checkPreStmt(const ReturnStmt *RS, CheckerContext &C) const {
210   ProgramStateRef State = C.getState();
211   if (isChildProcess(State))
212     reportBug("Return", C, "call _exit() instead");
213 }
214 
215 void ento::registerVforkChecker(CheckerManager &mgr) {
216   mgr.registerChecker<VforkChecker>();
217 }
218 
219 bool ento::shouldRegisterVforkChecker(const LangOptions &LO) {
220   return true;
221 }
222