MIGChecker.cpp 11 KB

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