xref: /freebsd/contrib/llvm-project/clang/lib/StaticAnalyzer/Checkers/MIGChecker.cpp (revision 349cc55c9796c4596a5b9904cd3281af295f878f)
10b57cec5SDimitry Andric //== MIGChecker.cpp - MIG calling convention checker ------------*- C++ -*--==//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file defines MIGChecker, a Mach Interface Generator calling convention
100b57cec5SDimitry Andric // checker. Namely, in MIG callback implementation the following rules apply:
110b57cec5SDimitry Andric // - When a server routine returns an error code that represents success, it
120b57cec5SDimitry Andric //   must take ownership of resources passed to it (and eventually release
130b57cec5SDimitry Andric //   them).
140b57cec5SDimitry Andric // - Additionally, when returning success, all out-parameters must be
150b57cec5SDimitry Andric //   initialized.
160b57cec5SDimitry Andric // - When it returns any other error code, it must not take ownership,
170b57cec5SDimitry Andric //   because the message and its out-of-line parameters will be destroyed
180b57cec5SDimitry Andric //   by the client that called the function.
190b57cec5SDimitry Andric // For now we only check the last rule, as its violations lead to dangerous
200b57cec5SDimitry Andric // use-after-free exploits.
210b57cec5SDimitry Andric //
220b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
230b57cec5SDimitry Andric 
24480093f4SDimitry Andric #include "clang/AST/Attr.h"
250b57cec5SDimitry Andric #include "clang/Analysis/AnyCall.h"
260b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
270b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
280b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/Checker.h"
290b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/CheckerManager.h"
30*349cc55cSDimitry Andric #include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h"
310b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
320b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
330b57cec5SDimitry Andric 
340b57cec5SDimitry Andric using namespace clang;
350b57cec5SDimitry Andric using namespace ento;
360b57cec5SDimitry Andric 
370b57cec5SDimitry Andric namespace {
380b57cec5SDimitry Andric class MIGChecker : public Checker<check::PostCall, check::PreStmt<ReturnStmt>,
390b57cec5SDimitry Andric                                   check::EndFunction> {
400b57cec5SDimitry Andric   BugType BT{this, "Use-after-free (MIG calling convention violation)",
410b57cec5SDimitry Andric              categories::MemoryError};
420b57cec5SDimitry Andric 
430b57cec5SDimitry Andric   // The checker knows that an out-of-line object is deallocated if it is
440b57cec5SDimitry Andric   // passed as an argument to one of these functions. If this object is
450b57cec5SDimitry Andric   // additionally an argument of a MIG routine, the checker keeps track of that
460b57cec5SDimitry Andric   // information and issues a warning when an error is returned from the
470b57cec5SDimitry Andric   // respective routine.
480b57cec5SDimitry Andric   std::vector<std::pair<CallDescription, unsigned>> Deallocators = {
490b57cec5SDimitry Andric #define CALL(required_args, deallocated_arg, ...)                              \
500b57cec5SDimitry Andric   {{{__VA_ARGS__}, required_args}, deallocated_arg}
510b57cec5SDimitry Andric       // E.g., if the checker sees a C function 'vm_deallocate' that is
520b57cec5SDimitry Andric       // defined on class 'IOUserClient' that has exactly 3 parameters, it knows
530b57cec5SDimitry Andric       // that argument #1 (starting from 0, i.e. the second argument) is going
540b57cec5SDimitry Andric       // to be consumed in the sense of the MIG consume-on-success convention.
550b57cec5SDimitry Andric       CALL(3, 1, "vm_deallocate"),
560b57cec5SDimitry Andric       CALL(3, 1, "mach_vm_deallocate"),
570b57cec5SDimitry Andric       CALL(2, 0, "mig_deallocate"),
580b57cec5SDimitry Andric       CALL(2, 1, "mach_port_deallocate"),
590b57cec5SDimitry Andric       CALL(1, 0, "device_deallocate"),
600b57cec5SDimitry Andric       CALL(1, 0, "iokit_remove_connect_reference"),
610b57cec5SDimitry Andric       CALL(1, 0, "iokit_remove_reference"),
620b57cec5SDimitry Andric       CALL(1, 0, "iokit_release_port"),
630b57cec5SDimitry Andric       CALL(1, 0, "ipc_port_release"),
640b57cec5SDimitry Andric       CALL(1, 0, "ipc_port_release_sonce"),
650b57cec5SDimitry Andric       CALL(1, 0, "ipc_voucher_attr_control_release"),
660b57cec5SDimitry Andric       CALL(1, 0, "ipc_voucher_release"),
670b57cec5SDimitry Andric       CALL(1, 0, "lock_set_dereference"),
680b57cec5SDimitry Andric       CALL(1, 0, "memory_object_control_deallocate"),
690b57cec5SDimitry Andric       CALL(1, 0, "pset_deallocate"),
700b57cec5SDimitry Andric       CALL(1, 0, "semaphore_dereference"),
710b57cec5SDimitry Andric       CALL(1, 0, "space_deallocate"),
720b57cec5SDimitry Andric       CALL(1, 0, "space_inspect_deallocate"),
730b57cec5SDimitry Andric       CALL(1, 0, "task_deallocate"),
740b57cec5SDimitry Andric       CALL(1, 0, "task_inspect_deallocate"),
750b57cec5SDimitry Andric       CALL(1, 0, "task_name_deallocate"),
760b57cec5SDimitry Andric       CALL(1, 0, "thread_deallocate"),
770b57cec5SDimitry Andric       CALL(1, 0, "thread_inspect_deallocate"),
780b57cec5SDimitry Andric       CALL(1, 0, "upl_deallocate"),
790b57cec5SDimitry Andric       CALL(1, 0, "vm_map_deallocate"),
800b57cec5SDimitry Andric       // E.g., if the checker sees a method 'releaseAsyncReference64()' that is
810b57cec5SDimitry Andric       // defined on class 'IOUserClient' that takes exactly 1 argument, it knows
820b57cec5SDimitry Andric       // that the argument is going to be consumed in the sense of the MIG
830b57cec5SDimitry Andric       // consume-on-success convention.
840b57cec5SDimitry Andric       CALL(1, 0, "IOUserClient", "releaseAsyncReference64"),
850b57cec5SDimitry Andric       CALL(1, 0, "IOUserClient", "releaseNotificationPort"),
860b57cec5SDimitry Andric #undef CALL
870b57cec5SDimitry Andric   };
880b57cec5SDimitry Andric 
890b57cec5SDimitry Andric   CallDescription OsRefRetain{"os_ref_retain", 1};
900b57cec5SDimitry Andric 
910b57cec5SDimitry Andric   void checkReturnAux(const ReturnStmt *RS, CheckerContext &C) const;
920b57cec5SDimitry Andric 
930b57cec5SDimitry Andric public:
940b57cec5SDimitry Andric   void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
950b57cec5SDimitry Andric 
960b57cec5SDimitry Andric   // HACK: We're making two attempts to find the bug: checkEndFunction
970b57cec5SDimitry Andric   // should normally be enough but it fails when the return value is a literal
980b57cec5SDimitry Andric   // that never gets put into the Environment and ends of function with multiple
990b57cec5SDimitry Andric   // returns get agglutinated across returns, preventing us from obtaining
1000b57cec5SDimitry Andric   // the return value. The problem is similar to https://reviews.llvm.org/D25326
1010b57cec5SDimitry Andric   // but now we step into it in the top-level function.
1020b57cec5SDimitry Andric   void checkPreStmt(const ReturnStmt *RS, CheckerContext &C) const {
1030b57cec5SDimitry Andric     checkReturnAux(RS, C);
1040b57cec5SDimitry Andric   }
1050b57cec5SDimitry Andric   void checkEndFunction(const ReturnStmt *RS, CheckerContext &C) const {
1060b57cec5SDimitry Andric     checkReturnAux(RS, C);
1070b57cec5SDimitry Andric   }
1080b57cec5SDimitry Andric 
1090b57cec5SDimitry Andric };
1100b57cec5SDimitry Andric } // end anonymous namespace
1110b57cec5SDimitry Andric 
1120b57cec5SDimitry Andric // A flag that says that the programmer has called a MIG destructor
1130b57cec5SDimitry Andric // for at least one parameter.
1140b57cec5SDimitry Andric REGISTER_TRAIT_WITH_PROGRAMSTATE(ReleasedParameter, bool)
1150b57cec5SDimitry Andric // A set of parameters for which the check is suppressed because
1160b57cec5SDimitry Andric // reference counting is being performed.
1170b57cec5SDimitry Andric REGISTER_SET_WITH_PROGRAMSTATE(RefCountedParameters, const ParmVarDecl *)
1180b57cec5SDimitry Andric 
1190b57cec5SDimitry Andric static const ParmVarDecl *getOriginParam(SVal V, CheckerContext &C,
1200b57cec5SDimitry Andric                                          bool IncludeBaseRegions = false) {
1210b57cec5SDimitry Andric   // TODO: We should most likely always include base regions here.
1220b57cec5SDimitry Andric   SymbolRef Sym = V.getAsSymbol(IncludeBaseRegions);
1230b57cec5SDimitry Andric   if (!Sym)
1240b57cec5SDimitry Andric     return nullptr;
1250b57cec5SDimitry Andric 
1260b57cec5SDimitry Andric   // If we optimistically assume that the MIG routine never re-uses the storage
1270b57cec5SDimitry Andric   // that was passed to it as arguments when it invalidates it (but at most when
1280b57cec5SDimitry Andric   // it assigns to parameter variables directly), this procedure correctly
1290b57cec5SDimitry Andric   // determines if the value was loaded from the transitive closure of MIG
1300b57cec5SDimitry Andric   // routine arguments in the heap.
1310b57cec5SDimitry Andric   while (const MemRegion *MR = Sym->getOriginRegion()) {
1320b57cec5SDimitry Andric     const auto *VR = dyn_cast<VarRegion>(MR);
1330b57cec5SDimitry Andric     if (VR && VR->hasStackParametersStorage() &&
1340b57cec5SDimitry Andric            VR->getStackFrame()->inTopFrame())
1350b57cec5SDimitry Andric       return cast<ParmVarDecl>(VR->getDecl());
1360b57cec5SDimitry Andric 
1370b57cec5SDimitry Andric     const SymbolicRegion *SR = MR->getSymbolicBase();
1380b57cec5SDimitry Andric     if (!SR)
1390b57cec5SDimitry Andric       return nullptr;
1400b57cec5SDimitry Andric 
1410b57cec5SDimitry Andric     Sym = SR->getSymbol();
1420b57cec5SDimitry Andric   }
1430b57cec5SDimitry Andric 
1440b57cec5SDimitry Andric   return nullptr;
1450b57cec5SDimitry Andric }
1460b57cec5SDimitry Andric 
1470b57cec5SDimitry Andric static bool isInMIGCall(CheckerContext &C) {
1480b57cec5SDimitry Andric   const LocationContext *LC = C.getLocationContext();
1490b57cec5SDimitry Andric   assert(LC && "Unknown location context");
1500b57cec5SDimitry Andric 
1510b57cec5SDimitry Andric   const StackFrameContext *SFC;
1520b57cec5SDimitry Andric   // Find the top frame.
1530b57cec5SDimitry Andric   while (LC) {
1540b57cec5SDimitry Andric     SFC = LC->getStackFrame();
1550b57cec5SDimitry Andric     LC = SFC->getParent();
1560b57cec5SDimitry Andric   }
1570b57cec5SDimitry Andric 
1580b57cec5SDimitry Andric   const Decl *D = SFC->getDecl();
1590b57cec5SDimitry Andric 
1600b57cec5SDimitry Andric   if (Optional<AnyCall> AC = AnyCall::forDecl(D)) {
1610b57cec5SDimitry Andric     // Even though there's a Sema warning when the return type of an annotated
1620b57cec5SDimitry Andric     // function is not a kern_return_t, this warning isn't an error, so we need
1630b57cec5SDimitry Andric     // an extra sanity check here.
1640b57cec5SDimitry Andric     // FIXME: AnyCall doesn't support blocks yet, so they remain unchecked
1650b57cec5SDimitry Andric     // for now.
1660b57cec5SDimitry Andric     if (!AC->getReturnType(C.getASTContext())
1670b57cec5SDimitry Andric              .getCanonicalType()->isSignedIntegerType())
1680b57cec5SDimitry Andric       return false;
1690b57cec5SDimitry Andric   }
1700b57cec5SDimitry Andric 
1710b57cec5SDimitry Andric   if (D->hasAttr<MIGServerRoutineAttr>())
1720b57cec5SDimitry Andric     return true;
1730b57cec5SDimitry Andric 
1740b57cec5SDimitry Andric   // See if there's an annotated method in the superclass.
1750b57cec5SDimitry Andric   if (const auto *MD = dyn_cast<CXXMethodDecl>(D))
1760b57cec5SDimitry Andric     for (const auto *OMD: MD->overridden_methods())
1770b57cec5SDimitry Andric       if (OMD->hasAttr<MIGServerRoutineAttr>())
1780b57cec5SDimitry Andric         return true;
1790b57cec5SDimitry Andric 
1800b57cec5SDimitry Andric   return false;
1810b57cec5SDimitry Andric }
1820b57cec5SDimitry Andric 
1830b57cec5SDimitry Andric void MIGChecker::checkPostCall(const CallEvent &Call, CheckerContext &C) const {
184*349cc55cSDimitry Andric   if (OsRefRetain.matches(Call)) {
1850b57cec5SDimitry Andric     // If the code is doing reference counting over the parameter,
1860b57cec5SDimitry Andric     // it opens up an opportunity for safely calling a destructor function.
1870b57cec5SDimitry Andric     // TODO: We should still check for over-releases.
1880b57cec5SDimitry Andric     if (const ParmVarDecl *PVD =
1890b57cec5SDimitry Andric             getOriginParam(Call.getArgSVal(0), C, /*IncludeBaseRegions=*/true)) {
1900b57cec5SDimitry Andric       // We never need to clean up the program state because these are
1910b57cec5SDimitry Andric       // top-level parameters anyway, so they're always live.
1920b57cec5SDimitry Andric       C.addTransition(C.getState()->add<RefCountedParameters>(PVD));
1930b57cec5SDimitry Andric     }
1940b57cec5SDimitry Andric     return;
1950b57cec5SDimitry Andric   }
1960b57cec5SDimitry Andric 
1970b57cec5SDimitry Andric   if (!isInMIGCall(C))
1980b57cec5SDimitry Andric     return;
1990b57cec5SDimitry Andric 
2000b57cec5SDimitry Andric   auto I = llvm::find_if(Deallocators,
2010b57cec5SDimitry Andric                          [&](const std::pair<CallDescription, unsigned> &Item) {
202*349cc55cSDimitry Andric                            return Item.first.matches(Call);
2030b57cec5SDimitry Andric                          });
2040b57cec5SDimitry Andric   if (I == Deallocators.end())
2050b57cec5SDimitry Andric     return;
2060b57cec5SDimitry Andric 
2070b57cec5SDimitry Andric   ProgramStateRef State = C.getState();
2080b57cec5SDimitry Andric   unsigned ArgIdx = I->second;
2090b57cec5SDimitry Andric   SVal Arg = Call.getArgSVal(ArgIdx);
2100b57cec5SDimitry Andric   const ParmVarDecl *PVD = getOriginParam(Arg, C);
2110b57cec5SDimitry Andric   if (!PVD || State->contains<RefCountedParameters>(PVD))
2120b57cec5SDimitry Andric     return;
2130b57cec5SDimitry Andric 
2145ffd83dbSDimitry Andric   const NoteTag *T =
2155ffd83dbSDimitry Andric     C.getNoteTag([this, PVD](PathSensitiveBugReport &BR) -> std::string {
2160b57cec5SDimitry Andric         if (&BR.getBugType() != &BT)
2170b57cec5SDimitry Andric           return "";
2180b57cec5SDimitry Andric         SmallString<64> Str;
2190b57cec5SDimitry Andric         llvm::raw_svector_ostream OS(Str);
2200b57cec5SDimitry Andric         OS << "Value passed through parameter '" << PVD->getName()
2210b57cec5SDimitry Andric            << "\' is deallocated";
2225ffd83dbSDimitry Andric         return std::string(OS.str());
2230b57cec5SDimitry Andric       });
2240b57cec5SDimitry Andric   C.addTransition(State->set<ReleasedParameter>(true), T);
2250b57cec5SDimitry Andric }
2260b57cec5SDimitry Andric 
2270b57cec5SDimitry Andric // Returns true if V can potentially represent a "successful" kern_return_t.
2280b57cec5SDimitry Andric static bool mayBeSuccess(SVal V, CheckerContext &C) {
2290b57cec5SDimitry Andric   ProgramStateRef State = C.getState();
2300b57cec5SDimitry Andric 
2310b57cec5SDimitry Andric   // Can V represent KERN_SUCCESS?
2320b57cec5SDimitry Andric   if (!State->isNull(V).isConstrainedFalse())
2330b57cec5SDimitry Andric     return true;
2340b57cec5SDimitry Andric 
2350b57cec5SDimitry Andric   SValBuilder &SVB = C.getSValBuilder();
2360b57cec5SDimitry Andric   ASTContext &ACtx = C.getASTContext();
2370b57cec5SDimitry Andric 
2380b57cec5SDimitry Andric   // Can V represent MIG_NO_REPLY?
2390b57cec5SDimitry Andric   static const int MigNoReply = -305;
2400b57cec5SDimitry Andric   V = SVB.evalEQ(C.getState(), V, SVB.makeIntVal(MigNoReply, ACtx.IntTy));
2410b57cec5SDimitry Andric   if (!State->isNull(V).isConstrainedTrue())
2420b57cec5SDimitry Andric     return true;
2430b57cec5SDimitry Andric 
2440b57cec5SDimitry Andric   // If none of the above, it's definitely an error.
2450b57cec5SDimitry Andric   return false;
2460b57cec5SDimitry Andric }
2470b57cec5SDimitry Andric 
2480b57cec5SDimitry Andric void MIGChecker::checkReturnAux(const ReturnStmt *RS, CheckerContext &C) const {
2490b57cec5SDimitry Andric   // It is very unlikely that a MIG callback will be called from anywhere
2500b57cec5SDimitry Andric   // within the project under analysis and the caller isn't itself a routine
2510b57cec5SDimitry Andric   // that follows the MIG calling convention. Therefore we're safe to believe
2520b57cec5SDimitry Andric   // that it's always the top frame that is of interest. There's a slight chance
2530b57cec5SDimitry Andric   // that the user would want to enforce the MIG calling convention upon
2540b57cec5SDimitry Andric   // a random routine in the middle of nowhere, but given that the convention is
2550b57cec5SDimitry Andric   // fairly weird and hard to follow in the first place, there's relatively
2560b57cec5SDimitry Andric   // little motivation to spread it this way.
2570b57cec5SDimitry Andric   if (!C.inTopFrame())
2580b57cec5SDimitry Andric     return;
2590b57cec5SDimitry Andric 
2600b57cec5SDimitry Andric   if (!isInMIGCall(C))
2610b57cec5SDimitry Andric     return;
2620b57cec5SDimitry Andric 
2630b57cec5SDimitry Andric   // We know that the function is non-void, but what if the return statement
2640b57cec5SDimitry Andric   // is not there in the code? It's not a compile error, we should not crash.
2650b57cec5SDimitry Andric   if (!RS)
2660b57cec5SDimitry Andric     return;
2670b57cec5SDimitry Andric 
2680b57cec5SDimitry Andric   ProgramStateRef State = C.getState();
2690b57cec5SDimitry Andric   if (!State->get<ReleasedParameter>())
2700b57cec5SDimitry Andric     return;
2710b57cec5SDimitry Andric 
2720b57cec5SDimitry Andric   SVal V = C.getSVal(RS);
2730b57cec5SDimitry Andric   if (mayBeSuccess(V, C))
2740b57cec5SDimitry Andric     return;
2750b57cec5SDimitry Andric 
2760b57cec5SDimitry Andric   ExplodedNode *N = C.generateErrorNode();
2770b57cec5SDimitry Andric   if (!N)
2780b57cec5SDimitry Andric     return;
2790b57cec5SDimitry Andric 
280a7dea167SDimitry Andric   auto R = std::make_unique<PathSensitiveBugReport>(
2810b57cec5SDimitry Andric       BT,
2820b57cec5SDimitry Andric       "MIG callback fails with error after deallocating argument value. "
2830b57cec5SDimitry Andric       "This is a use-after-free vulnerability because the caller will try to "
2840b57cec5SDimitry Andric       "deallocate it again",
2850b57cec5SDimitry Andric       N);
2860b57cec5SDimitry Andric 
2870b57cec5SDimitry Andric   R->addRange(RS->getSourceRange());
288fe6060f1SDimitry Andric   bugreporter::trackExpressionValue(
289fe6060f1SDimitry Andric       N, RS->getRetValue(), *R,
290fe6060f1SDimitry Andric       {bugreporter::TrackingKind::Thorough, /*EnableNullFPSuppression=*/false});
2910b57cec5SDimitry Andric   C.emitReport(std::move(R));
2920b57cec5SDimitry Andric }
2930b57cec5SDimitry Andric 
2940b57cec5SDimitry Andric void ento::registerMIGChecker(CheckerManager &Mgr) {
2950b57cec5SDimitry Andric   Mgr.registerChecker<MIGChecker>();
2960b57cec5SDimitry Andric }
2970b57cec5SDimitry Andric 
2985ffd83dbSDimitry Andric bool ento::shouldRegisterMIGChecker(const CheckerManager &mgr) {
2990b57cec5SDimitry Andric   return true;
3000b57cec5SDimitry Andric }
301