xref: /llvm-project/clang/lib/StaticAnalyzer/Checkers/MIGChecker.cpp (revision 75e74e077c9fed24c00fb5e12078df2b192841da)
1 //== MIGChecker.cpp - MIG calling convention checker ------------*- 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 MIGChecker, a Mach Interface Generator calling convention
10 // checker. Namely, in MIG callback implementation the following rules apply:
11 // - When a server routine returns an error code that represents success, it
12 //   must take ownership of resources passed to it (and eventually release
13 //   them).
14 // - Additionally, when returning success, all out-parameters must be
15 //   initialized.
16 // - When it returns any other error code, it must not take ownership,
17 //   because the message and its out-of-line parameters will be destroyed
18 //   by the client that called the function.
19 // For now we only check the last rule, as its violations lead to dangerous
20 // use-after-free exploits.
21 //
22 //===----------------------------------------------------------------------===//
23 
24 #include "clang/Analysis/AnyCall.h"
25 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
26 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
27 #include "clang/StaticAnalyzer/Core/Checker.h"
28 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
29 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
30 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
31 
32 using namespace clang;
33 using namespace ento;
34 
35 namespace {
36 class MIGChecker : public Checker<check::PostCall, check::PreStmt<ReturnStmt>,
37                                   check::EndFunction> {
38   BugType BT{this, "Use-after-free (MIG calling convention violation)",
39              categories::MemoryError};
40 
41   // The checker knows that an out-of-line object is deallocated if it is
42   // passed as an argument to one of these functions. If this object is
43   // additionally an argument of a MIG routine, the checker keeps track of that
44   // information and issues a warning when an error is returned from the
45   // respective routine.
46   std::vector<std::pair<CallDescription, unsigned>> Deallocators = {
47 #define CALL(required_args, deallocated_arg, ...)                              \
48   {{{__VA_ARGS__}, required_args}, deallocated_arg}
49       // E.g., if the checker sees a C function 'vm_deallocate' that is
50       // defined on class 'IOUserClient' that has exactly 3 parameters, it knows
51       // that argument #1 (starting from 0, i.e. the second argument) is going
52       // to be consumed in the sense of the MIG consume-on-success convention.
53       CALL(3, 1, "vm_deallocate"),
54       CALL(3, 1, "mach_vm_deallocate"),
55       CALL(2, 0, "mig_deallocate"),
56       CALL(2, 1, "mach_port_deallocate"),
57       CALL(1, 0, "device_deallocate"),
58       CALL(1, 0, "iokit_remove_connect_reference"),
59       CALL(1, 0, "iokit_remove_reference"),
60       CALL(1, 0, "iokit_release_port"),
61       CALL(1, 0, "ipc_port_release"),
62       CALL(1, 0, "ipc_port_release_sonce"),
63       CALL(1, 0, "ipc_voucher_attr_control_release"),
64       CALL(1, 0, "ipc_voucher_release"),
65       CALL(1, 0, "lock_set_dereference"),
66       CALL(1, 0, "memory_object_control_deallocate"),
67       CALL(1, 0, "pset_deallocate"),
68       CALL(1, 0, "semaphore_dereference"),
69       CALL(1, 0, "space_deallocate"),
70       CALL(1, 0, "space_inspect_deallocate"),
71       CALL(1, 0, "task_deallocate"),
72       CALL(1, 0, "task_inspect_deallocate"),
73       CALL(1, 0, "task_name_deallocate"),
74       CALL(1, 0, "thread_deallocate"),
75       CALL(1, 0, "thread_inspect_deallocate"),
76       CALL(1, 0, "upl_deallocate"),
77       CALL(1, 0, "vm_map_deallocate"),
78       // E.g., if the checker sees a method 'releaseAsyncReference64()' that is
79       // defined on class 'IOUserClient' that takes exactly 1 argument, it knows
80       // that the argument is going to be consumed in the sense of the MIG
81       // consume-on-success convention.
82       CALL(1, 0, "IOUserClient", "releaseAsyncReference64"),
83       CALL(1, 0, "IOUserClient", "releaseNotificationPort"),
84 #undef CALL
85   };
86 
87   void checkReturnAux(const ReturnStmt *RS, CheckerContext &C) const;
88 
89 public:
90   void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
91 
92   // HACK: We're making two attempts to find the bug: checkEndFunction
93   // should normally be enough but it fails when the return value is a literal
94   // that never gets put into the Environment and ends of function with multiple
95   // returns get agglutinated across returns, preventing us from obtaining
96   // the return value. The problem is similar to https://reviews.llvm.org/D25326
97   // but now we step into it in the top-level function.
98   void checkPreStmt(const ReturnStmt *RS, CheckerContext &C) const {
99     checkReturnAux(RS, C);
100   }
101   void checkEndFunction(const ReturnStmt *RS, CheckerContext &C) const {
102     checkReturnAux(RS, C);
103   }
104 
105   class Visitor : public BugReporterVisitor {
106   public:
107     void Profile(llvm::FoldingSetNodeID &ID) const {
108       static int X = 0;
109       ID.AddPointer(&X);
110     }
111 
112     std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
113         BugReporterContext &BRC, BugReport &R);
114   };
115 };
116 } // end anonymous namespace
117 
118 // FIXME: It's a 'const ParmVarDecl *' but there's no ready-made GDM traits
119 // specialization for this sort of types.
120 REGISTER_TRAIT_WITH_PROGRAMSTATE(ReleasedParameter, const void *)
121 
122 std::shared_ptr<PathDiagnosticPiece>
123 MIGChecker::Visitor::VisitNode(const ExplodedNode *N, BugReporterContext &BRC,
124                                BugReport &R) {
125   const auto *NewPVD = static_cast<const ParmVarDecl *>(
126       N->getState()->get<ReleasedParameter>());
127   const auto *OldPVD = static_cast<const ParmVarDecl *>(
128       N->getFirstPred()->getState()->get<ReleasedParameter>());
129   if (OldPVD == NewPVD)
130     return nullptr;
131 
132   assert(NewPVD && "What is deallocated cannot be un-deallocated!");
133   SmallString<64> Str;
134   llvm::raw_svector_ostream OS(Str);
135   OS << "Value passed through parameter '" << NewPVD->getName()
136      << "' is deallocated";
137 
138   PathDiagnosticLocation Loc =
139       PathDiagnosticLocation::create(N->getLocation(), BRC.getSourceManager());
140   return std::make_shared<PathDiagnosticEventPiece>(Loc, OS.str());
141 }
142 
143 static const ParmVarDecl *getOriginParam(SVal V, CheckerContext &C) {
144   SymbolRef Sym = V.getAsSymbol();
145   if (!Sym)
146     return nullptr;
147 
148   // If we optimistically assume that the MIG routine never re-uses the storage
149   // that was passed to it as arguments when it invalidates it (but at most when
150   // it assigns to parameter variables directly), this procedure correctly
151   // determines if the value was loaded from the transitive closure of MIG
152   // routine arguments in the heap.
153   while (const MemRegion *MR = Sym->getOriginRegion()) {
154     const auto *VR = dyn_cast<VarRegion>(MR);
155     if (VR && VR->hasStackParametersStorage() &&
156            VR->getStackFrame()->inTopFrame())
157       return cast<ParmVarDecl>(VR->getDecl());
158 
159     const SymbolicRegion *SR = MR->getSymbolicBase();
160     if (!SR)
161       return nullptr;
162 
163     Sym = SR->getSymbol();
164   }
165 
166   return nullptr;
167 }
168 
169 static bool isInMIGCall(CheckerContext &C) {
170   const LocationContext *LC = C.getLocationContext();
171   const StackFrameContext *SFC;
172   // Find the top frame.
173   while (LC) {
174     SFC = LC->getStackFrame();
175     LC = SFC->getParent();
176   }
177 
178   const Decl *D = SFC->getDecl();
179 
180   if (Optional<AnyCall> AC = AnyCall::forDecl(D)) {
181     // Even though there's a Sema warning when the return type of an annotated
182     // function is not a kern_return_t, this warning isn't an error, so we need
183     // an extra sanity check here.
184     // FIXME: AnyCall doesn't support blocks yet, so they remain unchecked
185     // for now.
186     if (!AC->getReturnType(C.getASTContext())
187              .getCanonicalType()->isSignedIntegerType())
188       return false;
189   }
190 
191   if (D->hasAttr<MIGServerRoutineAttr>())
192     return true;
193 
194   // See if there's an annotated method in the superclass.
195   if (const auto *MD = dyn_cast<CXXMethodDecl>(D))
196     for (const auto *OMD: MD->overridden_methods())
197       if (OMD->hasAttr<MIGServerRoutineAttr>())
198         return true;
199 
200   return false;
201 }
202 
203 void MIGChecker::checkPostCall(const CallEvent &Call, CheckerContext &C) const {
204   if (!isInMIGCall(C))
205     return;
206 
207   auto I = llvm::find_if(Deallocators,
208                          [&](const std::pair<CallDescription, unsigned> &Item) {
209                            return Call.isCalled(Item.first);
210                          });
211   if (I == Deallocators.end())
212     return;
213 
214   unsigned ArgIdx = I->second;
215   SVal Arg = Call.getArgSVal(ArgIdx);
216   const ParmVarDecl *PVD = getOriginParam(Arg, C);
217   if (!PVD)
218     return;
219 
220   C.addTransition(C.getState()->set<ReleasedParameter>(PVD));
221 }
222 
223 // Returns true if V can potentially represent a "successful" kern_return_t.
224 static bool mayBeSuccess(SVal V, CheckerContext &C) {
225   ProgramStateRef State = C.getState();
226 
227   // Can V represent KERN_SUCCESS?
228   if (!State->isNull(V).isConstrainedFalse())
229     return true;
230 
231   SValBuilder &SVB = C.getSValBuilder();
232   ASTContext &ACtx = C.getASTContext();
233 
234   // Can V represent MIG_NO_REPLY?
235   static const int MigNoReply = -305;
236   V = SVB.evalEQ(C.getState(), V, SVB.makeIntVal(MigNoReply, ACtx.IntTy));
237   if (!State->isNull(V).isConstrainedTrue())
238     return true;
239 
240   // If none of the above, it's definitely an error.
241   return false;
242 }
243 
244 void MIGChecker::checkReturnAux(const ReturnStmt *RS, CheckerContext &C) const {
245   // It is very unlikely that a MIG callback will be called from anywhere
246   // within the project under analysis and the caller isn't itself a routine
247   // that follows the MIG calling convention. Therefore we're safe to believe
248   // that it's always the top frame that is of interest. There's a slight chance
249   // that the user would want to enforce the MIG calling convention upon
250   // a random routine in the middle of nowhere, but given that the convention is
251   // fairly weird and hard to follow in the first place, there's relatively
252   // little motivation to spread it this way.
253   if (!C.inTopFrame())
254     return;
255 
256   if (!isInMIGCall(C))
257     return;
258 
259   // We know that the function is non-void, but what if the return statement
260   // is not there in the code? It's not a compile error, we should not crash.
261   if (!RS)
262     return;
263 
264   ProgramStateRef State = C.getState();
265   if (!State->get<ReleasedParameter>())
266     return;
267 
268   SVal V = C.getSVal(RS);
269   if (mayBeSuccess(V, C))
270     return;
271 
272   ExplodedNode *N = C.generateErrorNode();
273   if (!N)
274     return;
275 
276   auto R = llvm::make_unique<BugReport>(
277       BT,
278       "MIG callback fails with error after deallocating argument value. "
279       "This is a use-after-free vulnerability because the caller will try to "
280       "deallocate it again",
281       N);
282 
283   R->addRange(RS->getSourceRange());
284   bugreporter::trackExpressionValue(N, RS->getRetValue(), *R, false);
285   R->addVisitor(llvm::make_unique<Visitor>());
286   C.emitReport(std::move(R));
287 }
288 
289 void ento::registerMIGChecker(CheckerManager &Mgr) {
290   Mgr.registerChecker<MIGChecker>();
291 }
292 
293 bool ento::shouldRegisterMIGChecker(const LangOptions &LO) {
294   return true;
295 }
296