Coverage Report

Created: 2023-11-11 10:31

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