clang 20.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#include <optional>
39
40using namespace clang;
41using namespace ento;
42
43namespace {
44
45class VforkChecker : public Checker<check::PreCall, check::PostCall,
46 check::Bind, check::PreStmt<ReturnStmt>> {
47 const BugType BT{this, "Dangerous construct in a vforked process"};
48 mutable llvm::SmallSet<const IdentifierInfo *, 10> VforkAllowlist;
49 mutable const IdentifierInfo *II_vfork = nullptr;
50
51 static bool isChildProcess(const ProgramStateRef State);
52
53 bool isVforkCall(const Decl *D, CheckerContext &C) const;
54 bool isCallExplicitelyAllowed(const IdentifierInfo *II,
55 CheckerContext &C) const;
56
57 void reportBug(const char *What, CheckerContext &C,
58 const char *Details = nullptr) const;
59
60public:
61 VforkChecker() = default;
62
63 void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
64 void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
65 void checkBind(SVal L, SVal V, const Stmt *S, CheckerContext &C) const;
66 void checkPreStmt(const ReturnStmt *RS, CheckerContext &C) const;
67};
68
69} // end anonymous namespace
70
71// This trait holds region of variable that is assigned with vfork's
72// return value (this is the only region child is allowed to write).
73// VFORK_RESULT_INVALID means that we are in parent process.
74// VFORK_RESULT_NONE means that vfork's return value hasn't been assigned.
75// Other values point to valid regions.
76REGISTER_TRAIT_WITH_PROGRAMSTATE(VforkResultRegion, const void *)
77#define VFORK_RESULT_INVALID 0
78#define VFORK_RESULT_NONE ((void *)(uintptr_t)1)
79
80bool VforkChecker::isChildProcess(const ProgramStateRef State) {
81 return State->get<VforkResultRegion>() != VFORK_RESULT_INVALID;
82}
83
84bool VforkChecker::isVforkCall(const Decl *D, CheckerContext &C) const {
85 auto FD = dyn_cast_or_null<FunctionDecl>(D);
86 if (!FD || !C.isCLibraryFunction(FD))
87 return false;
88
89 if (!II_vfork) {
90 ASTContext &AC = C.getASTContext();
91 II_vfork = &AC.Idents.get("vfork");
92 }
93
94 return FD->getIdentifier() == II_vfork;
95}
96
97// Returns true iff ok to call function after successful vfork.
98bool VforkChecker::isCallExplicitelyAllowed(const IdentifierInfo *II,
99 CheckerContext &C) const {
100 if (VforkAllowlist.empty()) {
101 // According to manpage.
102 const char *ids[] = {
103 "_Exit",
104 "_exit",
105 "execl",
106 "execle",
107 "execlp",
108 "execv",
109 "execve",
110 "execvp",
111 "execvpe",
112 nullptr
113 };
114
115 ASTContext &AC = C.getASTContext();
116 for (const char **id = ids; *id; ++id)
117 VforkAllowlist.insert(&AC.Idents.get(*id));
118 }
119
120 return VforkAllowlist.count(II);
121}
122
123void VforkChecker::reportBug(const char *What, CheckerContext &C,
124 const char *Details) const {
125 if (ExplodedNode *N = C.generateErrorNode(C.getState())) {
127 llvm::raw_svector_ostream os(buf);
128
129 os << What << " is prohibited after a successful vfork";
130
131 if (Details)
132 os << "; " << Details;
133
134 auto Report = std::make_unique<PathSensitiveBugReport>(BT, os.str(), N);
135 // TODO: mark vfork call in BugReportVisitor
136 C.emitReport(std::move(Report));
137 }
138}
139
140// Detect calls to vfork and split execution appropriately.
141void VforkChecker::checkPostCall(const CallEvent &Call,
142 CheckerContext &C) const {
143 // We can't call vfork in child so don't bother
144 // (corresponding warning has already been emitted in checkPreCall).
145 ProgramStateRef State = C.getState();
146 if (isChildProcess(State))
147 return;
148
149 if (!isVforkCall(Call.getDecl(), C))
150 return;
151
152 // Get return value of vfork.
153 SVal VforkRetVal = Call.getReturnValue();
154 std::optional<DefinedOrUnknownSVal> DVal =
155 VforkRetVal.getAs<DefinedOrUnknownSVal>();
156 if (!DVal)
157 return;
158
159 // Get assigned variable.
160 const ParentMap &PM = C.getLocationContext()->getParentMap();
161 const Stmt *P = PM.getParentIgnoreParenCasts(Call.getOriginExpr());
162 const VarDecl *LhsDecl;
163 std::tie(LhsDecl, std::ignore) = parseAssignment(P);
164
165 // Get assigned memory region.
166 MemRegionManager &M = C.getStoreManager().getRegionManager();
167 const MemRegion *LhsDeclReg =
168 LhsDecl
169 ? M.getVarRegion(LhsDecl, C.getLocationContext())
170 : (const MemRegion *)VFORK_RESULT_NONE;
171
172 // Parent branch gets nonzero return value (according to manpage).
173 ProgramStateRef ParentState, ChildState;
174 std::tie(ParentState, ChildState) = C.getState()->assume(*DVal);
175 C.addTransition(ParentState);
176 ChildState = ChildState->set<VforkResultRegion>(LhsDeclReg);
177 C.addTransition(ChildState);
178}
179
180// Prohibit calls to functions in child process which are not explicitly
181// allowed.
182void VforkChecker::checkPreCall(const CallEvent &Call,
183 CheckerContext &C) const {
184 ProgramStateRef State = C.getState();
185 if (isChildProcess(State) &&
186 !isCallExplicitelyAllowed(Call.getCalleeIdentifier(), C))
187 reportBug("This function call", C);
188}
189
190// Prohibit writes in child process (except for vfork's lhs).
191void 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.
209void 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
215void ento::registerVforkChecker(CheckerManager &mgr) {
216 mgr.registerChecker<VforkChecker>();
217}
218
219bool ento::shouldRegisterVforkChecker(const CheckerManager &mgr) {
220 return true;
221}
#define V(N, I)
Definition: ASTContext.h:3341
StringRef P
const Decl * D
#define REGISTER_TRAIT_WITH_PROGRAMSTATE(Name, Type)
Declares a program state trait for type Type called Name, and introduce a type named NameTy.
#define VFORK_RESULT_INVALID
#define VFORK_RESULT_NONE
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:187
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
One of these records is kept for each identifier that is lexed.
Stmt * getParentIgnoreParenCasts(Stmt *) const
Definition: ParentMap.cpp:148
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition: Stmt.h:3029
Stmt - This represents one statement.
Definition: Stmt.h:84
Represents a variable declaration or definition.
Definition: Decl.h:879
Represents an abstract call to a function or method along a particular path.
Definition: CallEvent.h:153
CHECKER * registerChecker(AT &&... Args)
Used to register checkers.
const VarRegion * getVarRegion(const VarDecl *VD, const LocationContext *LC)
getVarRegion - Retrieve or create the memory region associated with a specified VarDecl and LocationC...
Definition: MemRegion.cpp:1002
MemRegion - The root abstract class for all memory regions.
Definition: MemRegion.h:97
SVal - This represents a symbolic expression, which can be either an L-value or an R-value.
Definition: SVals.h:55
std::optional< T > getAs() const
Convert to the specified SVal type, returning std::nullopt if this SVal is not of the desired type.
Definition: SVals.h:86
const MemRegion * getAsRegion() const
Definition: SVals.cpp:120
std::pair< const clang::VarDecl *, const clang::Expr * > parseAssignment(const Stmt *S)
The JSON file list parser is used to communicate input to InstallAPI.