MIGChecker.cpp 11 KB

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