xref: /llvm-project/clang/lib/StaticAnalyzer/Checkers/MIGChecker.cpp (revision 10dd12360934cb8ecfb803a4b72841e9ca8bf622)
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 KERN_SUCCESS, it must take ownership of
12 //   resources (and eventually release them).
13 // - Additionally, when returning KERN_SUCCESS, all out-parameters must be
14 //   initialized.
15 // - When it returns anything except KERN_SUCCESS it must not take ownership,
16 //   because the message and its descriptors will be destroyed by the server
17 //   function.
18 // For now we only check the last rule, as its violations lead to dangerous
19 // use-after-free exploits.
20 //
21 //===----------------------------------------------------------------------===//
22 
23 #include "clang/Analysis/AnyCall.h"
24 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
25 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
26 #include "clang/StaticAnalyzer/Core/Checker.h"
27 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
28 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
29 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
30 
31 using namespace clang;
32 using namespace ento;
33 
34 namespace {
35 class MIGChecker : public Checker<check::PostCall, check::PreStmt<ReturnStmt>,
36                                   check::EndFunction> {
37   BugType BT{this, "Use-after-free (MIG calling convention violation)",
38              categories::MemoryError};
39 
40   CallDescription vm_deallocate { "vm_deallocate", 3 };
41 
42   void checkReturnAux(const ReturnStmt *RS, CheckerContext &C) const;
43 
44 public:
45   void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
46 
47   // HACK: We're making two attempts to find the bug: checkEndFunction
48   // should normally be enough but it fails when the return value is a literal
49   // that never gets put into the Environment and ends of function with multiple
50   // returns get agglutinated across returns, preventing us from obtaining
51   // the return value. The problem is similar to https://reviews.llvm.org/D25326
52   // but now we step into it in the top-level function.
53   void checkPreStmt(const ReturnStmt *RS, CheckerContext &C) const {
54     checkReturnAux(RS, C);
55   }
56   void checkEndFunction(const ReturnStmt *RS, CheckerContext &C) const {
57     checkReturnAux(RS, C);
58   }
59 
60   class Visitor : public BugReporterVisitor {
61   public:
62     void Profile(llvm::FoldingSetNodeID &ID) const {
63       static int X = 0;
64       ID.AddPointer(&X);
65     }
66 
67     std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
68         BugReporterContext &BRC, BugReport &R);
69   };
70 };
71 } // end anonymous namespace
72 
73 // FIXME: It's a 'const ParmVarDecl *' but there's no ready-made GDM traits
74 // specialization for this sort of types.
75 REGISTER_TRAIT_WITH_PROGRAMSTATE(ReleasedParameter, const void *)
76 
77 std::shared_ptr<PathDiagnosticPiece>
78 MIGChecker::Visitor::VisitNode(const ExplodedNode *N, BugReporterContext &BRC,
79                                BugReport &R) {
80   const auto *NewPVD = static_cast<const ParmVarDecl *>(
81       N->getState()->get<ReleasedParameter>());
82   const auto *OldPVD = static_cast<const ParmVarDecl *>(
83       N->getFirstPred()->getState()->get<ReleasedParameter>());
84   if (OldPVD == NewPVD)
85     return nullptr;
86 
87   assert(NewPVD && "What is deallocated cannot be un-deallocated!");
88   SmallString<64> Str;
89   llvm::raw_svector_ostream OS(Str);
90   OS << "Value passed through parameter '" << NewPVD->getName()
91      << "' is deallocated";
92 
93   PathDiagnosticLocation Loc =
94       PathDiagnosticLocation::create(N->getLocation(), BRC.getSourceManager());
95   return std::make_shared<PathDiagnosticEventPiece>(Loc, OS.str());
96 }
97 
98 static const ParmVarDecl *getOriginParam(SVal V, CheckerContext &C) {
99   SymbolRef Sym = V.getAsSymbol();
100   if (!Sym)
101     return nullptr;
102 
103   const auto *VR = dyn_cast_or_null<VarRegion>(Sym->getOriginRegion());
104   if (VR && VR->hasStackParametersStorage() &&
105          VR->getStackFrame()->inTopFrame())
106     return cast<ParmVarDecl>(VR->getDecl());
107 
108   return nullptr;
109 }
110 
111 static bool isInMIGCall(CheckerContext &C) {
112   const LocationContext *LC = C.getLocationContext();
113   const StackFrameContext *SFC;
114   // Find the top frame.
115   while (LC) {
116     SFC = LC->getStackFrame();
117     LC = SFC->getParent();
118   }
119 
120   const Decl *D = SFC->getDecl();
121 
122   if (Optional<AnyCall> AC = AnyCall::forDecl(D)) {
123     // Even though there's a Sema warning when the return type of an annotated
124     // function is not a kern_return_t, this warning isn't an error, so we need
125     // an extra sanity check here.
126     // FIXME: AnyCall doesn't support blocks yet, so they remain unchecked
127     // for now.
128     if (!AC->getReturnType(C.getASTContext())
129              .getCanonicalType()->isSignedIntegerType())
130       return false;
131   }
132 
133   if (D->hasAttr<MIGServerRoutineAttr>())
134     return true;
135 
136   return false;
137 }
138 
139 void MIGChecker::checkPostCall(const CallEvent &Call, CheckerContext &C) const {
140   if (!isInMIGCall(C))
141     return;
142 
143   if (!Call.isGlobalCFunction())
144     return;
145 
146   if (!Call.isCalled(vm_deallocate))
147     return;
148 
149   // TODO: Unhardcode "1".
150   SVal Arg = Call.getArgSVal(1);
151   const ParmVarDecl *PVD = getOriginParam(Arg, C);
152   if (!PVD)
153     return;
154 
155   C.addTransition(C.getState()->set<ReleasedParameter>(PVD));
156 }
157 
158 void MIGChecker::checkReturnAux(const ReturnStmt *RS, CheckerContext &C) const {
159   // It is very unlikely that a MIG callback will be called from anywhere
160   // within the project under analysis and the caller isn't itself a routine
161   // that follows the MIG calling convention. Therefore we're safe to believe
162   // that it's always the top frame that is of interest. There's a slight chance
163   // that the user would want to enforce the MIG calling convention upon
164   // a random routine in the middle of nowhere, but given that the convention is
165   // fairly weird and hard to follow in the first place, there's relatively
166   // little motivation to spread it this way.
167   if (!C.inTopFrame())
168     return;
169 
170   if (!isInMIGCall(C))
171     return;
172 
173   // We know that the function is non-void, but what if the return statement
174   // is not there in the code? It's not a compile error, we should not crash.
175   if (!RS)
176     return;
177 
178   ProgramStateRef State = C.getState();
179   if (!State->get<ReleasedParameter>())
180     return;
181 
182   SVal V = C.getSVal(RS);
183   if (!State->isNonNull(V).isConstrainedTrue())
184     return;
185 
186   ExplodedNode *N = C.generateErrorNode();
187   if (!N)
188     return;
189 
190   auto R = llvm::make_unique<BugReport>(
191       BT,
192       "MIG callback fails with error after deallocating argument value. "
193       "This is a use-after-free vulnerability because the caller will try to "
194       "deallocate it again",
195       N);
196 
197   R->addRange(RS->getSourceRange());
198   bugreporter::trackExpressionValue(N, RS->getRetValue(), *R, false);
199   R->addVisitor(llvm::make_unique<Visitor>());
200   C.emitReport(std::move(R));
201 }
202 
203 void ento::registerMIGChecker(CheckerManager &Mgr) {
204   Mgr.registerChecker<MIGChecker>();
205 }
206 
207 bool ento::shouldRegisterMIGChecker(const LangOptions &LO) {
208   return true;
209 }
210