static VOID TestPrivateFunctions(VOID) { UNICODE_STRING ExAllocateCallBackName = RTL_CONSTANT_STRING(L"ExAllocateCallBack"); UNICODE_STRING ExFreeCallBackName = RTL_CONSTANT_STRING(L"ExFreeCallBack"); PEX_CALLBACK_ROUTINE_BLOCK CallbackBlock; INT CallbackContext; if (!ExAllocateCallBack) ExAllocateCallBack = MmGetSystemRoutineAddress(&ExAllocateCallBackName); if (!ExFreeCallBack) ExFreeCallBack = MmGetSystemRoutineAddress(&ExFreeCallBackName); if (skip(ExAllocateCallBack && ExFreeCallBack, "ExAllocateCallBack and/or ExFreeCallBack unavailable\n")) return; CallbackBlock = ExAllocateCallBack(ExCallbackFunction, &CallbackContext); ok(CallbackBlock != NULL, "CallbackBlock = NULL\n"); if (skip(CallbackBlock != NULL, "Allocating callback failed\n")) return; ok_eq_pointer(CallbackBlock->Function, ExCallbackFunction); ok_eq_pointer(CallbackBlock->Context, &CallbackContext); ok_eq_hex(KmtGetPoolTag(CallbackBlock), 'brbC'); ExFreeCallBack(CallbackBlock); }
NTSTATUS DriverEntry(IN PDRIVER_OBJECT DriverObject,IN PUNICODE_STRING RegistryPath) { KdPrintEx((DPFLTR_IHVDRIVER_ID,DPFLTR_ERROR_LEVEL,"[InjectEye] Entry \n")); { UNICODE_STRING SystemRoutineName ; RtlInitUnicodeString(&SystemRoutineName, L"ZwYieldExecution"); ZwWriteVirtualMemory=(PZwWriteVirtualMemory)((ULONG)MmGetSystemRoutineAddress(&SystemRoutineName )-0x14); RtlInitUnicodeString(&SystemRoutineName, L"ZwPulseEvent"); ZwProtectVirtualMemory=(PZwProtectVirtualMemory)((ULONG)MmGetSystemRoutineAddress(&SystemRoutineName )-0x14); Kernel32LoadLibraryAAddr=RetrieveFuncAddrFromKnownDLLs(L"\\KnownDLLs\\Kernel32.dll","LoadLibraryA",NULL); UrlmonDllMainCRTStartupAddr=RetrieveFuncAddrFromKnownDLLs(L"\\KnownDLLs\\urlmon.dll",NULL,UrlmonDllMainCRTStartupHeadInfo); KdPrintEx((DPFLTR_IHVDRIVER_ID,DPFLTR_ERROR_LEVEL,"[InjectEye] NtdllZwWriteVirtualMemory : 0x%08X\n",(ULONG)ZwWriteVirtualMemory)); KdPrintEx((DPFLTR_IHVDRIVER_ID,DPFLTR_ERROR_LEVEL,"[InjectEye] NtdllZwProtectVirtualMemory: 0x%08X\n",(ULONG)ZwProtectVirtualMemory)); KdPrintEx((DPFLTR_IHVDRIVER_ID,DPFLTR_ERROR_LEVEL,"[InjectEye] Kernel32!LoadLibraryAAddr : 0x%08X\n",(ULONG)Kernel32LoadLibraryAAddr)); KdPrintEx((DPFLTR_IHVDRIVER_ID,DPFLTR_ERROR_LEVEL,"[InjectEye] UrlmonDllMainCRTStartupAddr: 0x%08X\n",(ULONG)UrlmonDllMainCRTStartupAddr)); } if (Kernel32LoadLibraryAAddr && UrlmonDllMainCRTStartupAddr && ZwProtectVirtualMemory && ZwWriteVirtualMemory && HookFunc(TRUE)) { DriverObject->DriverUnload=InjectEyeUnload; return STATUS_SUCCESS; } return STATUS_UNSUCCESSFUL;; }
NTSTATUS kkll_m_notify_search(PKKLL_M_MEMORY_GENERIC generics, SIZE_T cbGenerics, PUCHAR * ptr, PULONG pRoutineMax, PKKLL_M_MEMORY_OFFSETS * pOffsets) { NTSTATUS status = STATUS_NOT_FOUND; PKKLL_M_MEMORY_GENERIC pGeneric; UNICODE_STRING stringStart, stringEnd; PUCHAR start, end; if(pGeneric = kkll_m_memory_getGenericFromBuild(generics, cbGenerics)) { RtlInitUnicodeString(&stringStart, pGeneric->start); RtlInitUnicodeString(&stringEnd, pGeneric->end); start = (PUCHAR) MmGetSystemRoutineAddress(&stringStart); end = (PUCHAR) MmGetSystemRoutineAddress(&stringEnd); if(start && end) { status = kkll_m_memory_genericPointerSearch(ptr, start, end, pGeneric->Search.Pattern, pGeneric->Search.Length, pGeneric->Offsets.off0); if(NT_SUCCESS(status)) { if(pRoutineMax) *pRoutineMax = pGeneric->Offsets.off1; if(pOffsets) *pOffsets = &pGeneric->Offsets; } } } return status; }
NTSTATUS FsRecLoadFileSystem(PDEVICE_OBJECT DeviceObject,LPWSTR DriverRegistryPath) { NTSTATUS Status = STATUS_IMAGE_ALREADY_LOADED; PDEVICE_EXTENSION DevExt,Ext; UNICODE_STRING DriverName; UNICODE_STRING FunName; PFN_ZwLoadDriver pfn_ZwLoadDriver; PFN_IoUnregisterFileSystem pfn_IoUnregisterFileSystem; PAGED_CODE(); RtlInitUnicodeString(&FunName,L"ZwLoadDriver"); pfn_ZwLoadDriver = (PFN_ZwLoadDriver)MmGetSystemRoutineAddress(&FunName); RtlInitUnicodeString(&FunName,L"IoUnregisterFileSystem"); pfn_IoUnregisterFileSystem = (PFN_IoUnregisterFileSystem)MmGetSystemRoutineAddress(&FunName); if(!pfn_ZwLoadDriver || pfn_IoUnregisterFileSystem) return Status; DevExt = (PDEVICE_EXTENSION)DeviceObject->DeviceExtension; if(DevExt->LoadStatus != DRIVER_LOADED) { KeEnterCriticalRegion(); KeWaitForSingleObject(FsRecLoadSync,Executive,KernelMode,FALSE,NULL); if(DevExt->LoadStatus == DRIVER_NOTLOAD) { RtlInitUnicodeString(&DriverName,DriverRegistryPath); Status = pfn_ZwLoadDriver(&DriverName); Ext = DevExt; while ( DevExt->LoadStatus != DRIVER_LOADING ) { Ext->LoadStatus = DRIVER_LOADING; Ext = (PDEVICE_EXTENSION)Ext->Device->DeviceExtension; } } Ext = DevExt; while ( Ext->LoadStatus != DRIVER_LOADED ) { pfn_IoUnregisterFileSystem(DeviceObject); DeviceObject = DevExt->Device; DevExt->LoadStatus = DRIVER_LOADED; Ext = (PDEVICE_EXTENSION)DeviceObject->DeviceExtension; } KeSetEvent(FsRecLoadSync,0,FALSE); KeLeaveCriticalRegion(); } return Status; }
NTSTATUS kkll_m_notify_init() { SIZE_T codeSize; NTSTATUS status = STATUS_NOT_FOUND; if(pPsSetCreateProcessNotifyRoutineEx = (PPSSETCREATEPROCESSNOTIFYROUTINEEX) MmGetSystemRoutineAddress(&uPsSetCreateProcessNotifyRoutineEx)) codeSize = (ULONG_PTR) kkll_m_notify_fake_ObjectPreCallback_end - (ULONG_PTR) kkll_m_notify_fake_ObjectPreCallback; if(kkll_m_notify_fakePre = (POB_PRE_OPERATION_CALLBACK) ExAllocatePoolWithTag(NonPagedPool, codeSize, POOL_TAG)) RtlCopyMemory(kkll_m_notify_fakePre, kkll_m_notify_fake_ObjectPreCallback, codeSize); codeSize = (ULONG_PTR) kkll_m_notify_fake_ObjectPostCallback_end - (ULONG_PTR) kkll_m_notify_fake_ObjectPostCallback; if(kkll_m_notify_fakePost = (POB_POST_OPERATION_CALLBACK) ExAllocatePoolWithTag(NonPagedPool, codeSize, POOL_TAG)) RtlCopyMemory(kkll_m_notify_fakePost, kkll_m_notify_fake_ObjectPostCallback, codeSize); if(pPsSetCreateProcessNotifyRoutineEx && kkll_m_notify_fakePre && kkll_m_notify_fakePost) status = STATUS_SUCCESS; else { if(kkll_m_notify_fakePre) { ExFreePoolWithTag(kkll_m_notify_fakePre, POOL_TAG); kkll_m_notify_fakePre = NULL; } if(kkll_m_notify_fakePost) { ExFreePoolWithTag(kkll_m_notify_fakePost, POOL_TAG); kkll_m_notify_fakePost = NULL; } } return status; }
//搜索PsLookProcessThreadByCide函数, 取得未导出的PspCidTable地址 BOOLEAN GetPspCidTableAddress() { ULONG length, functionAddress, current; UNICODE_STRING functionName; //获得PsLookupProcessThreadByCid路径 RtlInitUnicodeString(&functionName, L"PsLookupProcessThreadByCid"); functionAddress = (ULONG)MmGetSystemRoutineAddress(&functionName); if(functionAddress == 0) return FALSE; //搜索 push _PspCidTable指令, 获得PspCidTable地址 current = functionAddress; length = 0; do{ current += length; length = ade32_disasm((PVOID)current); if(length == 6 && (*(USHORT*)current == 0x35ff || *(USHORT*)current == 0x3d8b)) { current += 2; PspCidTable = *(PVOID*)(*(ULONG*)current); return TRUE; } }while(length != 0 && current <= functionAddress + 0x100); return FALSE; }
VOID FxUninitializeBugCheckDriverInfo() { UNICODE_STRING funcName; PKBUGCHECK_REASON_CALLBACK_RECORD callbackRecord; PFN_KE_DEREGISTER_BUGCHECK_REASON_CALLBACK funcPtr; // // Deregister callback. callbackRecord = &FxLibraryGlobals.BugCheckCallbackRecord; if (NULL == callbackRecord->CallbackRoutine) { goto Done; } // // The KeDeregisterBugCheckReasonCallback exists for xp sp1 and above. So // check whether this function is defined on the current OS and deregister // from the bugcheck callback only if this function is defined. // RtlInitUnicodeString(&funcName, L"KeDeregisterBugCheckReasonCallback"); funcPtr = (PFN_KE_DEREGISTER_BUGCHECK_REASON_CALLBACK) MmGetSystemRoutineAddress(&funcName); if (NULL == funcPtr) { goto Done; } funcPtr(callbackRecord); callbackRecord->CallbackRoutine = NULL; // // Release memory. // if (NULL == FxLibraryGlobals.BugCheckDriverInfo) { goto Done; } // // Dynamic KMDF framework is unloading, make sure there is only one entry // left in the driver info array; the framework lib was using this entry // to store its version. // ASSERT(1 == FxLibraryGlobals.BugCheckDriverInfoIndex); FxLibraryGlobals.BugCheckDriverInfoIndex = 0; FxLibraryGlobals.BugCheckDriverInfoCount = 0; MxMemory::MxFreePool(FxLibraryGlobals.BugCheckDriverInfo); FxLibraryGlobals.BugCheckDriverInfo = NULL; Done:; }
NTSTATUS OpenProcess( IN ULONG uPID, OUT PHANDLE pHandle, IN ACCESS_MASK DesiredAccess) { NTSTATUS rtStatus = STATUS_SUCCESS; PEPROCESS pEProcess = NULL; HANDLE hTagProcess = NULL; PULONG uPsProcessType = 0; UNICODE_STRING StrType; rtStatus = PsLookupProcessByProcessId((HANDLE)uPID, &pEProcess); if (NT_SUCCESS(rtStatus)) { RtlInitUnicodeString(&StrType, L"PsProcessType"); uPsProcessType = (PULONG)MmGetSystemRoutineAddress(&StrType); if (uPsProcessType) { rtStatus = ObOpenObjectByPointer(pEProcess, 0, 0, DesiredAccess, (POBJECT_TYPE)*uPsProcessType, UserMode, &hTagProcess); if (NT_SUCCESS(rtStatus)) { *pHandle = hTagProcess; } } ObfDereferenceObject(pEProcess); } return rtStatus; }
VOID SendEachProcessorDpc ( PKDEFERRED_ROUTINE Routine, PVOID Context, PVOID SysArg1, PVOID SysArg2 ) /*++ Routine Description This routine sends DPC to each processor in multiprocessor system Arguments Routine Deferred routine Context, SysArg1, SysArg2 Parameters, see MSDN doc for KeInitializeDpc, KeInsertQueueDpc Return Value None --*/ { UNICODE_STRING u; RtlInitUnicodeString (&u, L"KeFlushQueuedDpcs"); *(PVOID*)&pKeFlushQueuedDpcs = MmGetSystemRoutineAddress (&u); for (CCHAR i=0; i<KeNumberProcessors; i++) { KDPC Dpc; KdPrint(("SendEachProcessorDpc: processor [%d] in queue\n", i)); KeInitializeDpc (&Dpc, Routine, Context); KeSetTargetProcessorDpc (&Dpc, i); KeInsertQueueDpc (&Dpc, SysArg1, SysArg2); KdPrint(("SendEachProcessorDpc: processor [%d] completed its DPC\n", i)); } if (pKeFlushQueuedDpcs) { // Ensure that all DPCs are delivered. pKeFlushQueuedDpcs (); } else { KdPrint(("pKeFlushQueuedDpcs = NULL!!!\n")); } KdPrint(("SendEachProcessorDpc: all completed\n")); }
NTSTATUS getKeServiceDescriptorTable() { NTSTATUS retour = STATUS_NOT_FOUND; UCHAR PTRN_WALL_Ke[] = {0x00, 0x00, 0x4d, 0x0f, 0x45, 0xd3, 0x42, 0x3b, 0x44, 0x17, 0x10, 0x0f, 0x83}; LONG OFFS_WNO8_Ke = -19; LONG OFFS_WIN8_Ke = -16; PUCHAR refDebut = NULL, refFin = NULL; LONG offsetTo = 0; UNICODE_STRING maRoutine; PUCHAR baseSearch = NULL; if(KeServiceDescriptorTable) { retour = STATUS_SUCCESS; } else { RtlInitUnicodeString(&maRoutine, L"ZwUnloadKey"); if(baseSearch = (PUCHAR) MmGetSystemRoutineAddress(&maRoutine)) { refDebut= baseSearch - 21*PAGE_SIZE; refFin = baseSearch + 16*PAGE_SIZE; offsetTo = (INDEX_OS < INDEX_8) ? OFFS_WNO8_Ke : OFFS_WIN8_Ke; retour = genericPointerSearch((PUCHAR *) &KeServiceDescriptorTable, refDebut, refFin, PTRN_WALL_Ke, sizeof(PTRN_WALL_Ke), offsetTo); } } return retour; }
NTSTATUS RunTestSuite() { HOOK_TRACE_INFO hHook = { NULL }; NTSTATUS NtStatus; ULONG ACLEntries[1] = {0}; UNICODE_STRING SymbolName; KTIMER Timer; BOOLEAN HasInterface = FALSE; PFILE_OBJECT hEasyHookDrv; FORCE(EasyHookQueryInterface(EASYHOOK_INTERFACE_v_1, &Interface, &hEasyHookDrv)); HasInterface = TRUE; RtlInitUnicodeString(&SymbolName, L"KeCancelTimer"); /* The following shows how to install and remove local hooks... */ FORCE(Interface.LhInstallHook( MmGetSystemRoutineAddress(&SymbolName), KeCancelTimer_Hook, (PVOID)0x12345678, &hHook)); // won't invoke the hook handle because hooks are inactive after installation KeInitializeTimer(&Timer); KeCancelTimer(&Timer); // activate the hook for the current thread FORCE(Interface.LhSetInclusiveACL(ACLEntries, 1, &hHook)); // will be redirected into the handler... KeCancelTimer(&Timer); // this will NOT unhook the entry point. But the associated handler is never called again... Interface.LhUninstallHook(&hHook); // this will restore ALL entry points of currently rending removals issued by LhUninstallHook() Interface.LhWaitForPendingRemovals(); ObDereferenceObject(hEasyHookDrv); return STATUS_SUCCESS; ERROR_ABORT: if(HasInterface) { ObDereferenceObject(hEasyHookDrv); KdPrint(("\n[Error]: \"%S\" (code: %d)\n", Interface.RtlGetLastErrorString(), Interface.RtlGetLastError())); } else KdPrint(("\n[Error]: \"Unable to obtain EasyHook interface.\" (code: %d)\n", NtStatus)); return NtStatus; }
void ParaNdis_DebugInitialize(PVOID DriverObject,PVOID RegistryPath) { NDIS_STRING usRegister, usDeregister, usPrint; PVOID pr, pd; BOOLEAN res; WPP_INIT_TRACING(DriverObject, RegistryPath); NdisAllocateSpinLock(&CrashLock); KeInitializeCallbackRecord(&CallbackRecord); ParaNdis_PrepareBugCheckData(); NdisInitUnicodeString(&usPrint, L"vDbgPrintEx"); NdisInitUnicodeString(&usRegister, L"KeRegisterBugCheckReasonCallback"); NdisInitUnicodeString(&usDeregister, L"KeDeregisterBugCheckReasonCallback"); pd = MmGetSystemRoutineAddress(&usPrint); if (pd) PrintProcedure = (vDbgPrintExType)pd; pr = MmGetSystemRoutineAddress(&usRegister); pd = MmGetSystemRoutineAddress(&usDeregister); if (pr && pd) { BugCheckRegisterCallback = (KeRegisterBugCheckReasonCallbackType)pr; BugCheckDeregisterCallback = (KeDeregisterBugCheckReasonCallbackType)pd; } res = BugCheckRegisterCallback(&CallbackRecord, ParaNdis_OnBugCheck, KbCallbackSecondaryDumpData, "NetKvm"); DPrintf(0, ("[%s] Crash callback %sregistered", __FUNCTION__, res ? "" : "NOT ")); #ifdef OVERRIDE_DEBUG_BREAK if (sizeof(PVOID) == sizeof(ULONG)) { UCHAR replace[5] = {0xe9,0,0,0,0}; ULONG replacement; NDIS_STRING usDbgBreakPointName; NdisInitUnicodeString(&usDbgBreakPointName, L"DbgBreakPoint"); pDbgBreakPoint = (PUCHAR)MmGetSystemRoutineAddress(&usDbgBreakPointName); if (pDbgBreakPoint) { DPrintf(0, ("Replacing original BP handler at %p", pDbgBreakPoint)); replacement = RtlPointerToOffset(pDbgBreakPoint + 5, AnotherDbgBreak); RtlCopyMemory(replace + 1, &replacement, sizeof(replacement)); RtlCopyMemory(DbgBreakPointChunk, pDbgBreakPoint, sizeof(DbgBreakPointChunk)); RtlCopyMemory(pDbgBreakPoint, replace, sizeof(replace)); } } #endif }
/** * Retrieves the address of a function exported by NTOS or HAL. * * \param SystemRoutineName The name of the function. * * \return The address of the function, or NULL if the function could * not be found. */ PVOID KphGetSystemRoutineAddress( __in PWSTR SystemRoutineName ) { UNICODE_STRING systemRoutineName; PAGED_CODE(); RtlInitUnicodeString(&systemRoutineName, SystemRoutineName); return MmGetSystemRoutineAddress(&systemRoutineName); }
InLineHook() { UNICODE_STRING FuncName; RtlInitUnicodeString(&FuncName,L"ZwQuerySystemInformation"); MmGetSystemRoutineAddress(FuncName); strncpy(oldFunc,pFunc,5); pFunc[0] = xxxx; pFunc[1] = xxxx; pFunc[0] = xxxx; pFunc[1] = xxxx; pFunc[0] = xxxx;//inline hook修改的5个字节,jmp到我的函数 .....//剩下和ring3差不多了 }
static VOID BalloonInitializeAllocator( VOID ) { UNICODE_STRING Name; XM_ASSERT(__MmAllocatePagesForMdlEx == NULL); RtlInitUnicodeString(&Name, L"MmAllocatePagesForMdlEx"); __MmAllocatePagesForMdlEx = (PMM_ALLOCATE_PAGES_FOR_MDL_EX)(ULONG_PTR)MmGetSystemRoutineAddress(&Name); AllocatorInitialized = TRUE; }
PVOID GetFunctionAddressByName(WCHAR *wzFunction) { UNICODE_STRING uniFunction; PVOID AddrBase = NULL; if (wzFunction && wcslen(wzFunction) > 0) { RtlInitUnicodeString(&uniFunction, wzFunction); //常量指针 AddrBase = MmGetSystemRoutineAddress(&uniFunction); //在System 进程 第一个模块 Ntosknrl.exe ExportTable } return AddrBase; }
ULONG64 SymGetExportedAddress(IN PCHAR pszSymbolName) { ASSERTMSG("Passed symbol name is NULL", pszSymbolName != NULL); ASSERTMSG("SymbolEngine must be initialized prior to this call", bIsSymEngineInitialized == TRUE); ULONG64 u64Func = NULL; ULONG64 u64FuncBackup = NULL; ANSI_STRING szFunctionName; UNICODE_STRING uszFunctionName; u64Func = SymGetAddress(pszSymbolName); RtlInitAnsiString(&szFunctionName, pszSymbolName); // use UNICODE_STRING for MmGetSystemRoutineAddress memset(&uszFunctionName, 0, sizeof(UNICODE_STRING)); if(!NT_SUCCESS(RtlAnsiStringToUnicodeString(&uszFunctionName, &szFunctionName, TRUE))) { // if initialization failed, use obtained address, no matter what return u64Func; } u64FuncBackup = (ULONG64) MmGetSystemRoutineAddress(&uszFunctionName); if(u64Func == -1) { KdPrint(("[DEBUG] WARNING - Address of %s function not found - trying with the address retrieved from MmGetSystemRoutineAddress\n", szFunctionName.Buffer)); if(u64FuncBackup == NULL) { KdPrint(("[DEBUG] ERROR - MmGetSystemRoutineAddress for %s failed!\n", szFunctionName.Buffer)); RtlFreeUnicodeString(&uszFunctionName); return NULL; } else { // use address obtained from the MmGet... function as the relevant one RtlFreeUnicodeString(&uszFunctionName); return u64FuncBackup; } } // check if it differs from the address obtained from the kernel-mode else if(u64Func != u64FuncBackup) { // prefer kernel-mode (if not NULL) u64Func = (u64FuncBackup == NULL) ? u64Func : u64FuncBackup; RtlFreeUnicodeString(&uszFunctionName); return u64Func; } RtlFreeUnicodeString(&uszFunctionName); return u64Func; }
void ParaNdis_DebugInitialize() { NDIS_STRING usRegister, usDeregister, usPrint; PVOID pr, pd; BOOLEAN res; NdisAllocateSpinLock(&CrashLock); KeInitializeCallbackRecord(&CallbackRecord); ParaNdis_PrepareBugCheckData(); NdisInitUnicodeString(&usPrint, L"vDbgPrintEx"); NdisInitUnicodeString(&usRegister, L"KeRegisterBugCheckReasonCallback"); NdisInitUnicodeString(&usDeregister, L"KeDeregisterBugCheckReasonCallback"); pd = MmGetSystemRoutineAddress(&usPrint); if (pd) PrintProcedure = (vDbgPrintExType)pd; pr = MmGetSystemRoutineAddress(&usRegister); pd = MmGetSystemRoutineAddress(&usDeregister); if (pr && pd) { BugCheckRegisterCallback = (KeRegisterBugCheckReasonCallbackType)pr; BugCheckDeregisterCallback = (KeDeregisterBugCheckReasonCallbackType)pd; } res = BugCheckRegisterCallback(&CallbackRecord, ParaNdis_OnBugCheck, KbCallbackSecondaryDumpData, (const PUCHAR)"NetKvm"); DPrintf(0, ("[%s] Crash callback %sregistered\n", __FUNCTION__, res ? "" : "NOT ")); }
static void rtR0MemObjNtResolveDynamicApis(void) { ULONG uBuildNumber = 0; PsGetVersion(&g_uMajorVersion, &g_uMinorVersion, &uBuildNumber, NULL); #ifndef IPRT_TARGET_NT4 /* MmGetSystemRoutineAddress was introduced in w2k. */ UNICODE_STRING RoutineName; RtlInitUnicodeString(&RoutineName, L"MmProtectMdlSystemAddress"); g_pfnMmProtectMdlSystemAddress = (decltype(MmProtectMdlSystemAddress) *)MmGetSystemRoutineAddress(&RoutineName); #endif ASMCompilerBarrier(); g_fResolvedDynamicApis = true; }
//Code by Nukem: https://bitbucket.org/Nukem9/virtualdbghide static PVOID GetNtoskrnlBase() { UNICODE_STRING routineName; RtlInitUnicodeString(&routineName, L"DbgPrint"); ULONG_PTR addr = (ULONG_PTR)MmGetSystemRoutineAddress(&routineName); addr = (addr & ~(PAGE_SIZE - 1)); __try { while ((*(USHORT *)addr != IMAGE_DOS_SIGNATURE)) addr -= PAGE_SIZE; return (PVOID)addr; } __except (EXCEPTION_EXECUTE_HANDLER) { } return 0; }
static PVOID DetectMapIoSpace( _In_ PHYSICAL_ADDRESS PhysicalAddress, _In_ SIZE_T NumberOfBytes, _In_ MEMORY_CACHING_TYPE CacheType, _In_ ULONG Protect ) { PAGED_CODE(); UNICODE_STRING name; RtlInitUnicodeString(&name, L"MmMapIoSpaceEx"); pMmMapIoSpaceEx = (MmMapIoSpaceExFunc*)MmGetSystemRoutineAddress(&name); if (pMmMapIoSpaceEx) { MapIoSpace = NewMapIoSpace; } else { MapIoSpace = OldMapIoSpace; } return MapIoSpace(PhysicalAddress, NumberOfBytes, CacheType, Protect); }
PVOID GetKernelBase(OUT PULONG pSize) { NTSTATUS status = STATUS_SUCCESS; ULONG bytes = 0; PRTL_PROCESS_MODULES pMods = NULL; PVOID checkPtr = NULL; UNICODE_STRING routineName; ULONG i; // Already found if (g_KernelBase != NULL) { if (pSize) { *pSize = g_KernelSize; } return g_KernelBase; } RtlUnicodeStringInit (&routineName, L"NtOpenFile"); checkPtr = MmGetSystemRoutineAddress (&routineName); if (!checkPtr) { return NULL; } status = ZwQuerySystemInformation (SystemModuleInformation, 0, bytes, &bytes); if (bytes == 0) return NULL; pMods = (PRTL_PROCESS_MODULES)ExAllocatePoolWithTag (NonPagedPool, bytes, 'domP'); RtlZeroMemory (pMods, bytes); status = ZwQuerySystemInformation (SystemModuleInformation, pMods, bytes, &bytes); if (NT_SUCCESS(status)) { PRTL_PROCESS_MODULE_INFORMATION pMod = pMods->Modules; for (i = 0; i < pMods->NumberOfModules; i++) { if (checkPtr >= pMod[i].ImageBase && checkPtr < (PVOID)((PUCHAR)pMod[i].ImageBase + pMod[i].ImageSize)) { g_KernelBase = pMod[i].ImageBase; g_KernelSize = pMod[i].ImageSize; if (pSize) { *pSize = g_KernelSize; } } } } if (pMods) ExFreePoolWithTag (pMods, 'domP'); return g_KernelBase; }
VOID FindKiWaitFunc(PULONG64 *KiWaitNeverAddr, PULONG64 *KiWaitAlwaysAddr) { long Temp; PUCHAR StartAddress,i; UNICODE_STRING uniFuncName; WCHAR wzFunName[] = L"KeSetTimer"; RtlInitUnicodeString(&uniFuncName,wzFunName); StartAddress = (PUCHAR)MmGetSystemRoutineAddress(&uniFuncName); for(i=StartAddress; i<StartAddress+0xFF; i++) { if(*i==0x48 && *(i+1)==0x8B && *(i+2)==0x05) { memcpy(&Temp,i+3,4); *KiWaitNeverAddr=(PULONG64)((ULONGLONG)Temp + (ULONGLONG)i + 7); i=i+7; memcpy(&Temp,i+3,4); *KiWaitAlwaysAddr=(PULONG64)((ULONGLONG)Temp + (ULONGLONG)i + 7); return; } } }
static SshRegBool ssh_registry_platform_set_value(SshRegKey key, SshRegUnicodeString value, SshRegDataType type, SshRegData data, SshRegSize data_size) { SshSetValueKey fn_set_value_key; UNICODE_STRING fn_name; SSH_ASSERT(KeGetCurrentIrql() == PASSIVE_LEVEL); RtlInitUnicodeString(&fn_name, L"ZwSetValueKey"); fn_set_value_key = MmGetSystemRoutineAddress(&fn_name); if ((fn_set_value_key != NULL_FNPTR) && (NT_SUCCESS((*fn_set_value_key)(key, value, 0, type, data, data_size)))) return TRUE; else return FALSE; }
VOID FxUnregisterBugCheckCallback( __inout PFX_DRIVER_GLOBALS FxDriverGlobals ) { UNICODE_STRING funcName; PKBUGCHECK_REASON_CALLBACK_RECORD callbackRecord; PFN_KE_DEREGISTER_BUGCHECK_REASON_CALLBACK funcPtr; callbackRecord = &FxDriverGlobals->BugCheckCallbackRecord; if (NULL == callbackRecord->CallbackRoutine) { goto Done; } // // The KeDeregisterBugCheckReasonCallback exists for xp sp1 and above. So // check whether this function is defined on the current OS and deregister // from the bugcheck callback only if this function is defined. // RtlInitUnicodeString(&funcName, L"KeDeregisterBugCheckReasonCallback"); funcPtr = (PFN_KE_DEREGISTER_BUGCHECK_REASON_CALLBACK) MmGetSystemRoutineAddress(&funcName); if (NULL == funcPtr) { goto Done; } funcPtr(callbackRecord); callbackRecord->CallbackRoutine = NULL; // // Deregister this driver with driver tracker. // if (FxDriverGlobals->FxTrackDriverForMiniDumpLog) { FxLibraryGlobals.DriverTracker.Deregister(FxDriverGlobals); } Done:; }
static SshRegKey ssh_registry_platform_create_key(SshRegKey parent_key, SshRegPathUnicode path) { OBJECT_ATTRIBUTES attrs; SshCreateKey fn_create_key; UNICODE_STRING fn_name; Boolean close_parent_key = FALSE; SshRegKey ret_key = NULL; SSH_ASSERT(KeGetCurrentIrql() == PASSIVE_LEVEL); if (parent_key == HKEY_LOCAL_MACHINE) { parent_key = ssh_registry_platform_open_hklm(); if (parent_key == NULL) return NULL; close_parent_key = TRUE; } InitializeObjectAttributes(&attrs, path, OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE, parent_key, NULL); RtlInitUnicodeString(&fn_name, L"ZwCreateKey"); fn_create_key = MmGetSystemRoutineAddress(&fn_name); if (fn_create_key != NULL_FNPTR) { (*fn_create_key)(&ret_key, KEY_ALL_ACCESS, &attrs, 0, NULL, REG_OPTION_NON_VOLATILE, NULL); } if (close_parent_key) ssh_registry_key_close(parent_key); return ret_key; }
DECLHIDDEN(int) rtR0MpNotificationNativeInit(void) { /* * Try resolve the symbols. */ UNICODE_STRING RoutineName; RtlInitUnicodeString(&RoutineName, L"KeRegisterProcessorChangeCallback"); g_pfnKeRegisterProcessorChangeCallback = (PFNMYKEREGISTERPROCESSORCHANGECALLBACK)MmGetSystemRoutineAddress(&RoutineName); if (g_pfnKeRegisterProcessorChangeCallback) { RtlInitUnicodeString(&RoutineName, L"KeDeregisterProcessorChangeCallback"); g_pfnKeDeregisterProcessorChangeCallback = (PFNMYKEDEREGISTERPROCESSORCHANGECALLBACK)MmGetSystemRoutineAddress(&RoutineName); if (g_pfnKeDeregisterProcessorChangeCallback) { /* * Try call it. */ NTSTATUS ntRc = 0; g_hCallback = g_pfnKeRegisterProcessorChangeCallback(rtMpNotificationNtCallback, &ntRc, KE_PROCESSOR_CHANGE_ADD_EXISTING); if (g_hCallback != NULL) return VINF_SUCCESS; /* Genuine failure. */ int rc = RTErrConvertFromNtStatus(ntRc); AssertMsgFailed(("ntRc=%#x rc=%d\n", ntRc, rc)); return rc; } /* this shouldn't happen. */ AssertFailed(); } /* Not supported - success. */ g_pfnKeRegisterProcessorChangeCallback = NULL; g_pfnKeDeregisterProcessorChangeCallback = NULL; return VINF_SUCCESS; }
static SshRegBool ssh_registry_platform_delete_key(SshRegKey parent_key, SshRegPathUnicode path) { SshRegBool status = FALSE; SshRegKey key; SSH_ASSERT(KeGetCurrentIrql() == PASSIVE_LEVEL); key = ssh_registry_platform_open_key(parent_key, NULL, path); if (key != NULL) { SshDeleteKey fn_delete_key; UNICODE_STRING fn_name; RtlInitUnicodeString(&fn_name, L"ZwDeleteKey"); fn_delete_key = MmGetSystemRoutineAddress(&fn_name); if ((fn_delete_key != NULL_FNPTR) && (NT_SUCCESS((*fn_delete_key)(key)))) status = TRUE; } return status; }
//得到文件系统回调链表头地址 VOID GetListHeadAddr() { PUCHAR Addr; PUCHAR x,i; UNICODE_STRING IoRegisterFsRegistrationChangeString={0}; PVOID EnumParameter; WIN_VER_DETAIL WinVer; ULONG ulIoRegisterFsRegistrationChangeMountAware; RtlInitUnicodeString(&IoRegisterFsRegistrationChangeString, L"IoRegisterFsRegistrationChange"); Addr=MmGetSystemRoutineAddress(&IoRegisterFsRegistrationChangeString); IopFsNotifyChangeQueueHead = NULL; WinVer = GetWindowsVersion(); switch(WinVer) { case WINDOWS_VERSION_2K3_SP1_SP2: case WINDOWS_VERSION_XP: case WINDOWS_VERSION_7_7000: // Addr=*(ULONG*)((BYTE*)Addr+25); // IopFsNotifyChangeQueueHead=Addr; for (i=(ULONG)Addr;i < i+SizeOfProc(Addr);i++) { if (*i == 0xbe) { IopFsNotifyChangeQueueHead = *(PULONG)(i+1); if (MmIsAddressValidEx(IopFsNotifyChangeQueueHead)) { return; } } } break; case WINDOWS_VERSION_7_7600_UP: for (i=(ULONG)Addr;i < i+SizeOfProc(Addr);i++) { if (*i == 0xe8) { ulIoRegisterFsRegistrationChangeMountAware = *(PULONG)(i+1)+(ULONG)(i+5); if (MmIsAddressValidEx(ulIoRegisterFsRegistrationChangeMountAware)) { if (DebugOn) KdPrint(("ulIoRegisterFsRegistrationChangeMountAware:%08x\r\n",ulIoRegisterFsRegistrationChangeMountAware)); for (x=(ULONG)ulIoRegisterFsRegistrationChangeMountAware;x < x+SizeOfProc(ulIoRegisterFsRegistrationChangeMountAware);x++) { if (*x == 0xbf) { if (DebugOn) KdPrint(("x:%08x\r\n",x)); IopFsNotifyChangeQueueHead = *(PULONG)(x+1); if (MmIsAddressValidEx(IopFsNotifyChangeQueueHead)) { return; } break; } } } break; } } break; } }
//得到函数地址 ULONG GetFunctionAddr( IN PCWSTR FunctionName) { UNICODE_STRING UniCodeFunctionName; RtlInitUnicodeString( &UniCodeFunctionName, FunctionName ); return (ULONG)MmGetSystemRoutineAddress( &UniCodeFunctionName ); }