概述
在本文中,我们将介绍一种有趣的替代方案,用以替代备受推崇的由尼克·彼得森(Nick Peterson)开发的 InfinityHook。在微软发布并随后修补了 EtwpGetCycleCount 目标函数(且未对原作者进行任何致谢)之后,艾丹·库里(Aidan Khoury)发现了这一替代方法。该方法已在从早期 Windows 10 到最新 Windows 11 23H2 版本的系统中经过测试。借助此钩子(hook),可以实现多种不同的、实用的钩取操作。我们将探讨其中在我看来对抗恶意软件/反作弊用途而言最为有趣的一种。
免责声明
任何试图复现本文内容的人,都需要在其目标 NTOS 版本中找到相应的钩子/事件 ID。本文不会提供未来任何版本的钩子/事件 ID。本文中使用的值分别为 0x0F33:0x00501802。
首次测试是在 Windows 10 1903(19H1)版本上进行的;最新测试则是在 Windows 11 23H2 22631.2506 版本上完成的。不过,Windows 10 的早期版本也已通过测试和验证。首次测试仅是在发现该方法和进行概念验证开发时进行的。本文部分内容可能已过时,文中仅包含了从初稿重构代码后的更新内容。
Windows 内核中的常见钩取点
在 Windows 内核中,最常见的钩取目标是存储在全局表或自由浮动区域中的 .data 指针(即函数指针)。一个典型的例子就是 NtConvertBetweenAuxiliaryCounterAndPerformanceCounter 函数。许多游戏外挂开发者曾利用此函数作为“隐蔽通信”的手段(实际上它并不隐蔽),但它仍然是一个受欢迎的选择,也是绕过 PatchGuard 对系统 API 保护的一种滥用示例。使用该方法时,需要修改来自 HalPrivateDispatchTable 的函数指针,具体是修改指向 xKdEnumerateDebuggingDevices 的条目,然后从用户模式组件中获取 NTDLL 中的对应例程,并调用该函数。其中三个参数会被传递到调用的 HAL 函数中,这意味着用户可以在用户模式下灵活地使用和处理这些信息。
- // NtConvertBetweenAuxiliaryCounterAndPerformanceCounter 反编译代码片段
- //
- HalpTimerConvertConvert = HalTimerConvertAuxiliaryCounterToPerformanceCounter[0];
- if ( !ConvertAuxToPerf )
- HalpTimerConvertConvert = HalTimerConvertPerformanceCounterToAuxiliaryCounter[0];
- Result = (HalpTimerConvertConvert)(PerfCounterValue, &AuxCounter, v13);
复制代码 上述代码片段展示了如何根据参数指示(是否从辅助计数器转换为性能计数器)初始化指向 HAL 分发函数 HalTimerConvertXxx 的指针。基于这些信息,人们高度关注哪些机制可能被滥用,从而在不触发内置防篡改机制的情况下破坏系统安全或实现完全控制。因此,人们对以下内容产生了浓厚兴趣……
HalPrivateDispatchTable
HAL_PRIVATE_DISPATCH,通常被称为HalPrivateDispatchTable,是Windows操作系统(尤其是其硬件抽象层,即HAL)中的一个关键结构。该表在Windows操作系统与其所运行的硬件之间的交互中发挥着至关重要的作用,特别是对于那些未通过标准HAL接口暴露的硬件特定功能而言。简而言之,它只是一个函数指针表,表中的每个条目都对应一个特定的硬件功能,这些功能是根据Windows运行所在的平台需求量身定制的。其中一些条目的存在取决于平台类型(移动设备/工作站/终端)和启动参数,并且可能因Windows版本的不同而有所差异。正如前一段所述,HalPrivateDispatchTable的使用仅限于内核模式,驱动程序或其他内核组件会访问它以执行低级硬件操作。
这些操作大多涵盖从专门的硬件初始化到高级电源管理功能等各个方面。它是关乎系统稳定性和安全性的关键数据结构;我们接下来会深入探讨其中一些功能的重要性,不过,如果你熟悉InfinityHook的话,我相信你也能猜到个中缘由。
这个结构体有个令人遗憾之处,那就是相关文档通常非常匮乏,因为它涉及Windows内部更复杂、更低层次的方面。它主要吸引的是经验丰富的Windows内核开发人员,或是那些从事贴近硬件层面编程工作的人员。此处提取的大多数细节均是通过多种资源(见参考文献部分)以及对相关组件进行独立的逆向工程而获得的。以下是HalPrivateDispatchTable的详细布局。
- struct HAL_PRIVATE_DISPATCH
- {
- unsigned int Version;
- BUS_HANDLER *(*HalHandlerForBus)(INTERFACE_TYPE, unsigned int);
- BUS_HANDLER *(*HalHandlerForConfigSpace)(BUS_DATA_TYPE, unsigned int);
- void (*HalLocateHiberRanges)(void *);
- int (*HalRegisterBusHandler)(INTERFACE_TYPE, BUS_DATA_TYPE, unsigned int, INTERFACE_TYPE, unsigned int, unsigned int, int (*)(BUS_HANDLER *), BUS_HANDLER **);
- void (*HalSetWakeEnable)(unsigned __int8);
- int (*HalSetWakeAlarm)(unsigned __int64, unsigned __int64);
- unsigned __int8 (*HalPciTranslateBusAddress)(INTERFACE_TYPE, unsigned int, LARGE_INTEGER, unsigned int *, LARGE_INTEGER *);
- int (*HalPciAssignSlotResources)(UNICODE_STRING *, UNICODE_STRING *, DRIVER_OBJECT *, DEVICE_OBJECT *, INTERFACE_TYPE, unsigned int, unsigned int, CM_RESOURCE_LIST **);
- void (*HalHaltSystem)();
- unsigned __int8 (*HalFindBusAddressTranslation)(LARGE_INTEGER, unsigned int *, LARGE_INTEGER *, unsigned __int64 *, unsigned __int8);
- unsigned __int8 (*HalResetDisplay)();
- int (*HalAllocateMapRegisters)(_ADAPTER_OBJECT *, unsigned int, unsigned int, MAP_REGISTER_ENTRY *);
- int (*KdSetupPciDeviceForDebugging)(void *, DEBUG_DEVICE_DESCRIPTOR *);
- int (*KdReleasePciDeviceForDebugging)(DEBUG_DEVICE_DESCRIPTOR *);
- void *(*KdGetAcpiTablePhase0)(LOADER_PARAMETER_BLOCK *, unsigned int);
- void (*KdCheckPowerButton)();
- unsigned __int8 (*HalVectorToIDTEntry)(unsigned int);
- void *(*KdMapPhysicalMemory64)(LARGE_INTEGER, unsigned int, unsigned __int8);
- void (*KdUnmapVirtualAddress)(void *, unsigned int, unsigned __int8);
- unsigned int (*KdGetPciDataByOffset)(unsigned int, unsigned int, void *, unsigned int, unsigned int);
- unsigned int (*KdSetPciDataByOffset)(unsigned int, unsigned int, void *, unsigned int, unsigned int);
- unsigned int (*HalGetInterruptVectorOverride)(INTERFACE_TYPE, unsigned int, unsigned int, unsigned int, unsigned __int8 *, unsigned __int64 *);
- int (*HalGetVectorInputOverride)(unsigned int, GROUP_AFFINITY *, unsigned int *, KINTERRUPT_POLARITY *, INTERRUPT_REMAPPING_INFO *);
- int (*HalLoadMicrocode)(void *);
- int (*HalUnloadMicrocode)();
- int (*HalPostMicrocodeUpdate)();
- int (*HalAllocateMessageTargetOverride)(DEVICE_OBJECT *, GROUP_AFFINITY *, unsigned int, KINTERRUPT_MODE, unsigned __int8, unsigned int *, unsigned __int8 *, unsigned int *);
- void (*HalFreeMessageTargetOverride)(DEVICE_OBJECT *, unsigned int, GROUP_AFFINITY *);
- int (*HalDpReplaceBegin)(HAL_DP_REPLACE_PARAMETERS *, void **);
- void (*HalDpReplaceTarget)(void *);
- int (*HalDpReplaceControl)(unsigned int, void *);
- void (*HalDpReplaceEnd)(void *);
- void (*HalPrepareForBugcheck)(unsigned int);
- unsigned __int8 (*HalQueryWakeTime)(unsigned __int64 *, unsigned __int64 *);
- void (*HalReportIdleStateUsage)(unsigned __int8, KAFFINITY_EX *);
- void (*HalTscSynchronization)(unsigned __int8, unsigned int *);
- int (*HalWheaInitProcessorGenericSection)(WHEA_ERROR_RECORD_SECTION_DESCRIPTOR *, WHEA_PROCESSOR_GENERIC_ERROR_SECTION *);
- void (*HalStopLegacyUsbInterrupts)(SYSTEM_POWER_STATE);
- int (*HalReadWheaPhysicalMemory)(LARGE_INTEGER, unsigned int, void *);
- int (*HalWriteWheaPhysicalMemory)(LARGE_INTEGER, unsigned int, void *);
- int (*HalDpMaskLevelTriggeredInterrupts)();
- int (*HalDpUnmaskLevelTriggeredInterrupts)();
- int (*HalDpGetInterruptReplayState)(void *, void **);
- int (*HalDpReplayInterrupts)(void *);
- unsigned __int8 (*HalQueryIoPortAccessSupported)();
- int (*KdSetupIntegratedDeviceForDebugging)(void *, DEBUG_DEVICE_DESCRIPTOR *);
- int (*KdReleaseIntegratedDeviceForDebugging)(DEBUG_DEVICE_DESCRIPTOR *);
- void (*HalGetEnlightenmentInformation)(HAL_INTEL_ENLIGHTENMENT_INFORMATION *);
- void *(*HalAllocateEarlyPages)(LOADER_PARAMETER_BLOCK *, unsigned int, unsigned __int64 *, unsigned int);
- void *(*HalMapEarlyPages)(unsigned __int64, unsigned int, unsigned int);
- void *Dummy1;
- void *Dummy2;
- void (*HalNotifyProcessorFreeze)(unsigned __int8, unsigned __int8);
- int (*HalPrepareProcessorForIdle)(unsigned int);
- void (*HalRegisterLogRoutine)(HAL_LOG_REGISTER_CONTEXT *);
- void (*HalResumeProcessorFromIdle)();
- void *Dummy;
- unsigned int (*HalVectorToIDTEntryEx)(unsigned int);
- int (*HalSecondaryInterruptQueryPrimaryInformation)(INTERRUPT_VECTOR_DATA *, unsigned int *);
- int (*HalMaskInterrupt)(unsigned int, unsigned int);
- int (*HalUnmaskInterrupt)(unsigned int, unsigned int);
- unsigned __int8 (*HalIsInterruptTypeSecondary)(unsigned int, unsigned int);
- int (*HalAllocateGsivForSecondaryInterrupt)(char *, unsigned __int16, unsigned int *);
- int (*HalAddInterruptRemapping)(unsigned int, unsigned int, PCI_BUSMASTER_DESCRIPTOR *, unsigned __int8, INTERRUPT_VECTOR_DATA *, unsigned int);
- void (*HalRemoveInterruptRemapping)(unsigned int, unsigned int, PCI_BUSMASTER_DESCRIPTOR *, unsigned __int8, INTERRUPT_VECTOR_DATA *, unsigned int);
- void (*HalSaveAndDisableHvEnlightenment)();
- void (*HalRestoreHvEnlightenment)();
- void (*HalFlushIoBuffersExternalCache)(MDL *, unsigned __int8);
- void (*HalFlushExternalCache)(unsigned __int8);
- int (*HalPciEarlyRestore)(_SYSTEM_POWER_STATE);
- int (*HalGetProcessorId)(unsigned int, unsigned int *, unsigned int *);
- int (*HalAllocatePmcCounterSet)(unsigned int, _KPROFILE_SOURCE *, unsigned int, struct _HAL_PMC_COUNTERS **);
- void (*HalCollectPmcCounters)(struct HAL_PMC_COUNTERS *, unsigned __int64 *);
- void (*HalFreePmcCounterSet)(struct HAL_PMC_COUNTERS *);
- int (*HalProcessorHalt)(unsigned int, void *, int (*)(void *));
- unsigned __int64 (*HalTimerQueryCycleCounter)(unsigned __int64 *);
- void *Dummy3;
- void (*HalPciMarkHiberPhase)();
- int (*HalQueryProcessorRestartEntryPoint)(LARGE_INTEGER *);
- int (*HalRequestInterrupt)(unsigned int);
- int (*HalEnumerateUnmaskedInterrupts)(unsigned __int8 (*)(void *, HAL_UNMASKED_INTERRUPT_INFORMATION *), void *, HAL_UNMASKED_INTERRUPT_INFORMATION *);
- void (*HalFlushAndInvalidatePageExternalCache)(LARGE_INTEGER);
- int (*KdEnumerateDebuggingDevices)(void *, DEBUG_DEVICE_DESCRIPTOR *, KD_CALLBACK_ACTION (*)(DEBUG_DEVICE_DESCRIPTOR *));
- void (*HalFlushIoRectangleExternalCache)(_MDL *, unsigned int, unsigned int, unsigned int, unsigned int, unsigned __int8);
- void (*HalPowerEarlyRestore)(unsigned int);
- int (*HalQueryCapsuleCapabilities)(void *, unsigned int, unsigned __int64 *, unsigned int *);
- int (*HalUpdateCapsule)(void *, unsigned int, LARGE_INTEGER);
- unsigned __int8 (*HalPciMultiStageResumeCapable)();
- void (*HalDmaFreeCrashDumpRegisters)(unsigned int);
- unsigned __int8 (*HalAcpiAoacCapable)();
- int (*HalInterruptSetDestination)(INTERRUPT_VECTOR_DATA *, GROUP_AFFINITY *, unsigned int *);
- void (*HalGetClockConfiguration)(HAL_CLOCK_TIMER_CONFIGURATION *);
- void (*HalClockTimerActivate)(unsigned __int8);
- void (*HalClockTimerInitialize)();
- void (*HalClockTimerStop)();
- int (*HalClockTimerArm)(_HAL_CLOCK_TIMER_MODE, unsigned __int64, unsigned __int64 *);
- unsigned __int8 (*HalTimerOnlyClockInterruptPending)();
- void *(*HalAcpiGetMultiNode)();
- void (*(*HalPowerSetRebootHandler)(void (*)(unsigned int, volatile int *)))(unsigned int, volatile int *);
- void (*HalIommuRegisterDispatchTable)(HAL_IOMMU_DISPATCH *);
- void (*HalTimerWatchdogStart)();
- void (*HalTimerWatchdogResetCountdown)();
- void (*HalTimerWatchdogStop)();
- unsigned __int8 (*HalTimerWatchdogGeneratedLastReset)();
- int (*HalTimerWatchdogTriggerSystemReset)(unsigned __int8);
- int (*HalInterruptVectorDataToGsiv)(INTERRUPT_VECTOR_DATA *, unsigned int *);
- int (*HalInterruptGetHighestPriorityInterrupt)(unsigned int *, unsigned __int8 *);
- int (*HalProcessorOn)(unsigned int);
- int (*HalProcessorOff)();
- int (*HalProcessorFreeze)();
- int (*HalDmaLinkDeviceObjectByToken)(unsigned __int64, DEVICE_OBJECT *);
- int (*HalDmaCheckAdapterToken)(unsigned __int64);
- void *Dummy4;
- int (*HalTimerConvertPerformanceCounterToAuxiliaryCounter)(unsigned __int64, unsigned __int64 *, unsigned __int64 *);
- int (*HalTimerConvertAuxiliaryCounterToPerformanceCounter)(unsigned __int64, unsigned __int64 *, unsigned __int64 *);
- int (*HalTimerQueryAuxiliaryCounterFrequency)(unsigned __int64 *);
- int (*HalConnectThermalInterrupt)(unsigned __int8 (*)(KINTERRUPT *, void *));
- unsigned __int8 (*HalIsEFIRuntimeActive)();
- unsigned __int8 (*HalTimerQueryAndResetRtcErrors)(unsigned __int8);
- void (*HalAcpiLateRestore)();
- int (*KdWatchdogDelayExpiration)(unsigned __int64 *);
- int (*HalGetProcessorStats)(HAL_PROCESSOR_STAT_TYPE, unsigned int, unsigned int, unsigned __int64 *);
- unsigned __int64 (*HalTimerWatchdogQueryDueTime)(unsigned __int8);
- int (*HalConnectSyntheticInterrupt)(unsigned __int8 (*)(KINTERRUPT *, void *));
- void (*HalPreprocessNmi)(unsigned int);
- int (*HalEnumerateEnvironmentVariablesWithFilter)(unsigned int, unsigned __int8 (*)(const _GUID *, const wchar_t *), void *, unsigned int *);
- int (*HalCaptureLastBranchRecordStack)(unsigned int, HAL_LBR_ENTRY *, unsigned int *);
- unsigned __int8 (*HalClearLastBranchRecordStack)();
- int (*HalConfigureLastBranchRecord)(unsigned int, unsigned int);
- unsigned __int8 (*HalGetLastBranchInformation)(unsigned int *, unsigned int *);
- void (*HalResumeLastBranchRecord)(unsigned __int8);
- int (*HalStartLastBranchRecord)(unsigned int, unsigned int *);
- int (*HalStopLastBranchRecord)(unsigned int);
- int (*HalIommuBlockDevice)(void *);
- int (*HalIommuUnblockDevice)(EXT_IOMMU_DEVICE_ID *, void **);
- int (*HalGetIommuInterface)(unsigned int, DMA_IOMMU_INTERFACE *);
- int (*HalRequestGenericErrorRecovery)(void *, unsigned int *);
- int (*HalTimerQueryHostPerformanceCounter)(unsigned __int64 *);
- int (*HalTopologyQueryProcessorRelationships)(unsigned int, unsigned int, unsigned __int8 *, unsigned __int8 *, unsigned __int8 *, unsigned int *, unsigned int *);
- void (*HalInitPlatformDebugTriggers)();
- void (*HalRunPlatformDebugTriggers)(unsigned __int8);
- void *(*HalTimerGetReferencePage)();
- int (*HalGetHiddenProcessorPowerInterface)(HIDDEN_PROCESSOR_POWER_INTERFACE *);
- unsigned int (*HalGetHiddenProcessorPackageId)(unsigned int);
- unsigned int (*HalGetHiddenPackageProcessorCount)(unsigned int);
- int (*HalGetHiddenProcessorApicIdByIndex)(unsigned int, unsigned int *);
- int (*HalRegisterHiddenProcessorIdleState)(unsigned int, unsigned __int64);
- void (*HalIommuReportIommuFault)(unsigned __int64, FAULT_INFORMATION *);
- unsigned __int8 (*HalIommuDmaRemappingCapable)(EXT_IOMMU_DEVICE_ID *, unsigned int *);
- };
复制代码
目标发现
掌握了HalPrivateDispatchTable的信息和结构后,如果我们重新审视InfinityHook所使用的机制,就会发现原始代码已被打补丁,但仍存在一些值得关注的功能。所有这些功能都出现在EtwpLogKernelEvent(ETW内核事件日志记录函数)中。我们可以看到其中三个似乎是很不错的目标。
- if( /* etw init conditions */ )
- {
- v33 = EtwpReserveTraceBuffer(v14, v15 + 0x10, &v59, &v55, a6);
- //
- // ... [etc]
- //
- goto LABEL_19;
- }
- if ( /* etw init conditions */ )
- {
- v34 = EtwpReserveWithPebsIndex(v14, 0x524, v15, &v59, &v55, a6);
- }
- else
- {
- //
- // ... [etc]
- //
- v34 = EtwpReserveWithPmcCounters(v14, a5, v15, &v59, &v55, a6);
- }
复制代码 目前,尚未有任何关于EtwpReserveWithPmcCounters函数的公开信息。如果ETW记录器以正确的方式进行了设置,该函数就会被执行;而当我们查看其内部实现时,会发现另一个非常适合进行补丁修改(即挂钩或篡改)的目标。
- signed __int64 __fastcall EtwpReserveWithPmcCounters(
- WMI_LOGGER_CONTEXT *LoggerContext,
- UINT16 HookId,
- UINT64 AuxSize,
- void *BufferHandle,
- LARGE_INTEGER *TimeStamp,
- UINT64 Flags)
- {
- volatile unsigned int CountersCount;
- unsigned int CtrIndex;
- unsigned int RequiredSize;
- unsigned __int8 CurrentIrql;
- struct_TraceBuffer *TraceBuffer;
- struct_TraceBuffer *pTracebuf;
- struct _HAL_PMC_COUNTERS *PmcEnabledForProc;
- _ETW_PMC_SUPPORT *PmcData;
-
- PmcData = LoggerContext->PmcData;
- CountersCount = PmcData->CountersCount;
- CtrIndex = 8 * CountersCount + 0x10;
- RequiredSize = CtrIndex + AuxSize;
- CurrentIrql = KeGetCurrentIrql();
- if ( CurrentIrql < DISPATCH_LEVEL )
- {
- KeGetCurrentIrql();
- __writecr8(DISPATCH_LEVEL);
- }
- TraceBuffer = EtwpReserveTraceBuffer(&LoggerContext->LoggerId, RequiredSize, BufferHandle, TimeStamp, Flags);
- pTracebuf = TraceBuffer;
- if ( TraceBuffer )
- {
- TraceBuffer->TimeStamp = *TimeStamp;
- TraceBuffer->TotalCounters = RequiredSize;
- TraceBuffer->HookId = HookId;
- TraceBuffer->Flags = Flags | (CountersCount << 8) | 0xC0110000;
- PmcEnabledForProc = PmcData->ProcessorCtrs[KeGetPcr()->Prcb.Number];
- if ( PmcEnabledForProc )
- HalPrivateDispatch->HalpCollectPmcCounters(PmcEnabledForProc, &TraceBuffer->Counters);
- else
- memset(&TraceBuffer->Counters, 0, 8 * CountersCount);
- if ( CurrentIrql < DISPATCH_LEVEL )
- __writecr8(CurrentIrql);
- return pTracebuf + CtrIndex;
- }
- else
- {
- if ( CurrentIrql < DISPATCH_LEVEL )
- __writecr8(CurrentIrql);
- return 0;
- }
- }
复制代码 我们关注的目标显而易见,就是HalPrivateDispatch->HalpCollectPmcCounters(...)(通过HalPrivateDispatch表调用HalpCollectPmcCounters函数)。如果我们在实时系统中追踪调用链,会发现类似这样的流程:
- KernelBase.dll!SleepEx
- |- ntdll.dll!NtDelayExecution
- | |- ntoskrnl.exe!KiSystemServiceExitPico
- | | |- ntoskrnl.exe!PerfInfoLogSysCallEntry
- | | | |- ntoskrnl.exe!EtwTraceKernelEvent
- | | | | |- ntoskrnl.exe!EtwpLogKernelEvent
- | | | | | |- ntoskrnl.exe!EtwpReservePmcCounters
- | | | | | | |- ntoskrnl.exe!HalpCollectPmcCounters ---> | 这些情况仅在ETW记录器被正确配置时才会发生。
复制代码 ETW的配置将导致NT内核记录器(NT Kernel Logger)输出包含如下信息的内容:
- Logger Name : NT Kernel Logger
- Logger Id : ffff
- Logger Thread Id : 00000000000012A4
- Buffer Size : 8192
- Maximum Buffers : 118
- Minimum Buffers : 96
- Number of Buffers : 118
- Free Buffers : 70
- Buffers Written : 106898
- Events Lost : 0
- Log Buffers Lost : 0
- Real Time Buffers Lost: 0
- Flush Timer : 0
- Age Limit : 0
- Log File Mode : Secure PersistOnHybridShutdown SystemLogger
- Maximum File Size : 0
- Log Filename : EdgyNameHere
- Trace Flags : SYSCALL
- PoolTagFilter : *
复制代码 这只是一个快速验证,旨在直观展示我们能够以符合保护引导(PG,Protected Guard)要求的方式挂钩系统调用(SYSCALL)(即不会导致机器出现错误检查并蓝屏崩溃)。
自己动手丰衣足食……
那么,我们该如何利用这些信息呢?方法相对简单,让我们来一步步说明。
- 定位HalPrivateDispatchTable。
- 定位系统调用处理程序(System Call Handler)。
- 获取用于记录系统调用(SYSCALL)的ETW(事件跟踪)事件ID。
- 以编程方式配置ETW会话。
- 配置适当的事件跟踪类数据。
- 替换HalPrivateDispatchTable中的指针。
- 尽情享受又一个符合保护引导(PG)要求的挂钩机制。
δ 定位HalPrivateDispatchTable
获取指向HalPrivateDispatchTable的指针,可按如下方式实现:
- UNICODE_STRING target = RTL_CONSTANT_STRING( L"HalPrivateDispatchTable" );
- HalPrivateDispatchTable = reinterpret_cast< PHAL_PRIVATE_DISPATCH_TABLE >( MmGetSystemRoutineAddress( &target ) );
-
- if ( !HalPrivateDispatchTable )
- return STATUS_RESOURCE_UNAVAILABLE;
复制代码 有关HAL_PRIVATE_DISPATCH_TABLE的定义,请参考上文给出的详细结构。
δ 额外的ETW配置
要使该功能正常运行,需注意:除了构建跟踪属性结构并将其修改为启用系统调用(SYSCALL)跟踪外,还必须通过ZwTraceControl函数配置各种跟踪控制参数。为此,您至少需要处理ZwTraceControl函数的以下操作码:EtwStartLoggerCode(启动记录器)、EtwStopLoggerCode(停止记录器)和EtwUpdateLoggerCode(更新记录器)。以下是概念验证代码中的部分示例:
- switch (operation) {
- case kl_trace_operation::start: {
- status = ZwTraceControl(EtwStartLoggerCode, pproperty, sizeof(KL_TRACE_PROPERTIES), pproperty, sizeof(KL_TRACE_PROPERTIES), &return_length);
- break;
- }
- case kl_trace_operation::end: {
- status = ZwTraceControl(EtwStopLoggerCode, pproperty, sizeof(KL_TRACE_PROPERTIES), pproperty, sizeof(KL_TRACE_PROPERTIES), &return_length);
- break;
- }
- case kl_trace_operation::syscall: {
- pproperty->EnableFlags |= EVENT_TRACE_FLAG_SYSTEMCALL;
- status = ZwTraceControl(EtwUpdateLoggerCode, pproperty, sizeof(KL_TRACE_PROPERTIES), pproperty, sizeof(KL_TRACE_PROPERTIES), &return_length);
- break;
- }
- }
复制代码
- const GUID session_guid = { 0x9E814AAD, 0x3204, 0x11D2, { 0x9A, 0x82, 0x0, 0x60, 0x8, 0xA8, 0x69, 0x39 } };
- pproperty = nt::trace::build_property( L"NT Kernel Logger", &session_guid, EVENT_TRACE_BUFFERING_MODE );
复制代码 除此之外,我们还需要通过ZwSetSystemInformation函数并使用SystemPerformanceTraceInformation类来配置一些跟踪信息块,以设置计数器列表和性能分析信息,从而让性能监控计数器(PMC)收集例程能够正常运行。具体而言,需要配置的信息包括EventTraceProfileCounterListInformation(事件跟踪性能计数器列表信息)和EventTraceProfileEventListInformation(事件跟踪性能事件列表信息)。为节省篇幅,本文未包含相关代码。
δ HalCollectPmcCounters 挂钩机制
以下代码片段是挂钩例程中所需的全部内容,用于在系统调用(SYSCALL)跟踪期间全局应用该挂钩。具体操作包括:遍历调用栈,验证挂钩ID/事件ID是否与目标事件匹配;若匹配,则替换调用栈中包含目标系统例程地址的元素。
- void process_syscall(stack<64>& sp) {
- const auto target_fn = reinterpret_cast<void**>(sp.at(9));
-
- // Example that replaces the return address on stack for NtQuerySystemInformation
- // with our hk_NtQuerySystemInformation, allowing us to hook the call system wide
- // in a PG-compliant manner.
- //
- if (*target_fn == o__nt_query_system_information)
- *target_fn = &hkd__nt_query_system_information;
- }
-
- void hkd__hal_collect_pmc_counters(HAL_PMC_COUNTERS* pmc_ctrs, unsigned long long* trace_buffer_end)
- {
- // Call original to populate appropriate data structures; avoid unnecessary overhead.
- //
- o__hal_collect_pmc_counters(pmc_ctrs, trace_buffer_end);
-
- if (!pmc_ctrs || !trace_buffer_end)
- return;
-
- const auto hook_id = *reinterpret_cast<uint32_t>(reinterpret_cast<uintptr_t>(trace_buffer_end) - 10);
- if (hook_id != target_value_1)
- return;
-
- stack<64> stk(get_pcr()->prcb->rsp_base, _AddressOfReturnAddress());
-
- auto is_correct_event_target = [target_value_1, target_value_0](stack<64>& sp) {
- const auto event_id_1 = *sp.as<uint16_t*>();
- const auto event_id_0 = *sp.next().as<uint32_t*>();
- return event_id_1 == target_value_1 && event_id_0 == target_value_0;
- };
-
- auto curr_stack = stk.find_frame( is_correct_event_target );
- if (!curr_stack.valid())
- return;
-
- curr_stack += 2;
-
- auto target_sp = curr_stack.find_first_within({ syscall_handler_begin, syscall_handler_end });
-
- if(target_sp.valid())
- process_syscall(target_sp);
- }
复制代码
δ NtQuerySystemInformation 挂钩机制
由于我们需要一个测试用例来验证该挂钩机制,我提供了相应的挂钩代码及辅助函数,供有意进行一定程度复现的读者参考。
- static NTSTATUS hkd__nt_query_system_information(
- SYSTEM_INFORMATION_CLASS system_information_class,
- PVOID system_information,
- ULONG system_information_length,
- PULONG return_length
- ) {
- NTSTATUS status = o_NtQuerySystemInformation(system_information_class, system_information, system_information_length, return_length);
-
- if (is_target_process()) {
- log_system_information(system_information_class, system_information, system_information_length, status);
- if (NT_SUCCESS(status)) {
- modify_system_information(system_information_class, system_information, system_information_length);
- }
- }
-
- return status;
- }
-
- static bool is_target_process() {
- return !strcmp(PsGetProcessImageFileName(PsGetCurrentProcess()), "<target>");
- }
-
- static void log_system_information(SYSTEM_INFORMATION_CLASS system_information_class, PVOID system_information, ULONG system_information_length, NTSTATUS status) {
- const char* class_name = xnt::to_string(system_information_class);
- const char* process_name = PsGetProcessImageFileName(PsGetCurrentProcess());
- ULONG_PTR process_id = (ULONG_PTR)PsGetProcessId(PsGetCurrentProcess());
-
- if (class_name == nullptr) {
- LOG_INFO("%s (%I64d) :: NtQuerySystemInformation( %#x, 0x%p, %#x )", process_name, process_id, system_information_class, system_information, system_information_length);
- } else {
- LOG_INFO("%s (%I64d) :: NtQuerySystemInformation( %s, 0x%p, %#x )", process_name, process_id, class_name, system_information, system_information_length);
- }
- }
-
- static void modify_system_information(SYSTEM_INFORMATION_CLASS system_information_class, PVOID system_information, ULONG system_information_length) {
- PMDL mdl = IoAllocateMdl(system_information, system_information_length, FALSE, FALSE, NULL);
-
- if (!mdl) {
- LOG_INFO("Failed to allocate MDL in %s\n", __FUNCTION__);
- return;
- }
-
- __try {
- MmProbeAndLockPages(mdl, UserMode, IoWriteAccess);
- PVOID buffer = MmGetSystemAddressForMdlSafe(mdl, NormalPagePriority | MdlMappingNoExecute);
-
- if (!buffer) {
- goto __exit;
- }
-
- if (system_information_class == SystemKernelDebuggerInformation) {
- auto kdbg_info = reinterpret_cast<PSYSTEM_KERNEL_DEBUGGER_INFORMATION>(buffer);
- kdbg_info->KernelDebuggerEnabled = FALSE;
- kdbg_info->KernelDebuggerNotPresent = TRUE;
- } else if (system_information_class == SystemCodeIntegrityInformation) {
- auto code_integrity_info = reinterpret_cast<PSYSTEM_CODEINTEGRITY_INFORMATION>(buffer);
- code_integrity_info->CodeIntegrityOptions &= ~CODEINTEGRITY_OPTION_TESTSIGN;
- code_integrity_info->CodeIntegrityOptions |= CODEINTEGRITY_OPTION_ENABLED;
- }
- }
- __except (EXCEPTION_EXECUTE_HANDLER) {
- status = GetExceptionCode();
- LOG_INFO("Exception in %s :: %#x\n", __FUNCTION__, status);
- IoFreeMdl(mdl);
- }
- //
- // ...additional handling and resource release...
- //
- }
复制代码
可探测性分析
值得注意的是,与其他所有基于事件跟踪(ETW)的挂钩机制类似,该挂钩可通过调用栈(call-stack)分析被轻易检测。例如,验证 HalPrivateDispatchTable 的完整性即为一个潜在的检测路径。不过,通过调用栈伪造(call-stack spoofing)技术可绕过此类基于调用栈的检测。尽管存在多种探测该挂钩使用痕迹的方法(其中不乏颇具技术深度的案例,甚至可单独撰写专题文章),但为保持内容简洁,本文暂不展开讨论。
演示效果图
完成所有操作步骤后,本示例的日志输出如下:
结论
这种以符合PG原则的方式挂钩系统调用(SYSCALL)的方法颇具趣味,但其实际用途远比表面所见更为广泛。我撰写此博文旨在介绍这一技术,未来还将探讨其在系统调用之外更广泛的应用场景。内核操作监控与合规性实现的方式多种多样,但其中多数需要深厚的技术背景,且缺乏能简化阐述的配套资源。其中一项技术计划在后续文章中详细展开,但内容可能较为复杂。未来研究方向包括:持续探索TracePoint和事件跟踪(ETW)API,挖掘更多可用于间接控制系统操作的间接机制。
致谢
在此,我必须向以下人士致以诚挚感谢:
若您对相关研究感兴趣,欢迎通过 Twitter 联系 @daaximus 或 @aidankhoury。一如既往,感谢各位读者的关注,祝一切顺利!
原文链接
|