diff --git a/.clang-format b/.clang-format index 09eafac..8fef44f 100644 --- a/.clang-format +++ b/.clang-format @@ -1,9 +1,9 @@ BasedOnStyle: webkit AccessModifierOffset: -4 -AlignAfterOpenBracket: Align -AlignConsecutiveAssignments: true -AlignConsecutiveDeclarations: true +AlignAfterOpenBracket: AlwaysBreak +AlignConsecutiveAssignments: false +AlignConsecutiveDeclarations: false AlignConsecutiveMacros: true @@ -73,7 +73,7 @@ MaxEmptyLinesToKeep: 1 NamespaceIndentation: None #All PointerAlignment: Left ReflowComments: true -SortIncludes: false +SortIncludes: true SpaceAfterCStyleCast: false SpaceBeforeAssignmentOperators: true diff --git a/driver/apc.c b/driver/apc.c index e3ceec1..6c00065 100644 --- a/driver/apc.c +++ b/driver/apc.c @@ -137,7 +137,8 @@ QueryActiveApcContextsForCompletion() switch (entry->context_id) { case APC_CONTEXT_ID_STACKWALK: - FreeApcStackwalkApcContextInformation((PAPC_STACKWALK_CONTEXT)entry); + FreeApcStackwalkApcContextInformation( + (PAPC_STACKWALK_CONTEXT)entry); FreeApcContextStructure(entry); break; } diff --git a/driver/callbacks.c b/driver/callbacks.c index 2819b37..9e881b9 100644 --- a/driver/callbacks.c +++ b/driver/callbacks.c @@ -2,27 +2,28 @@ #include "driver.h" -#include "pool.h" -#include "thread.h" -#include "modules.h" -#include "imports.h" -#include "session.h" #include "crypt.h" +#include "imports.h" +#include "modules.h" +#include "pool.h" +#include "session.h" +#include "thread.h" #include "util.h" #include "lib/stdlib.h" -#include "containers/tree.h" #include "containers/map.h" +#include "containers/tree.h" #define PROCESS_HASHMAP_BUCKET_COUNT 101 STATIC BOOLEAN -EnumHandleCallback(_In_ PHANDLE_TABLE HandleTable, - _In_ PHANDLE_TABLE_ENTRY Entry, - _In_ HANDLE Handle, - _In_ PVOID Context); +EnumHandleCallback( + _In_ PHANDLE_TABLE HandleTable, + _In_ PHANDLE_TABLE_ENTRY Entry, + _In_ HANDLE Handle, + _In_ PVOID Context); #ifdef ALLOC_PRAGMA # pragma alloc_text(PAGE, ObPostOpCallbackRoutine) @@ -75,15 +76,15 @@ CleanupThreadListOnDriverUnload() VOID CleanupDriverListOnDriverUnload() { - PDRIVER_LIST_HEAD head = GetDriverList(); - PLIST_ENTRY entry = NULL; + PDRIVER_LIST_HEAD head = GetDriverList(); + PLIST_ENTRY entry = NULL; + PDRIVER_LIST_ENTRY driver = NULL; ImpKeAcquireGuardedMutex(&head->lock); while (!IsListEmpty(&head->list_entry)) { entry = RemoveHeadList(&head->list_entry); - PDRIVER_LIST_ENTRY driverEntry = - CONTAINING_RECORD(entry, DRIVER_LIST_ENTRY, list_entry); + driver = CONTAINING_RECORD(entry, DRIVER_LIST_ENTRY, list_entry); ExFreePoolWithTag(entry, POOL_TAG_DRIVER_LIST); } @@ -94,8 +95,8 @@ VOID EnumerateDriverListWithCallbackRoutine( _In_ DRIVERLIST_CALLBACK_ROUTINE CallbackRoutine, _In_opt_ PVOID Context) { - PDRIVER_LIST_HEAD head = GetDriverList(); - PLIST_ENTRY list_entry = NULL; + PDRIVER_LIST_HEAD head = GetDriverList(); + PLIST_ENTRY list_entry = NULL; PDRIVER_LIST_ENTRY driver_entry = NULL; ImpKeAcquireGuardedMutex(&head->lock); @@ -114,13 +115,15 @@ EnumerateDriverListWithCallbackRoutine( } VOID -DriverListEntryToExtendedModuleInfo(_In_ PDRIVER_LIST_ENTRY Entry, - _Out_ PRTL_MODULE_EXTENDED_INFO Extended) +DriverListEntryToExtendedModuleInfo( + _In_ PDRIVER_LIST_ENTRY Entry, _Out_ PRTL_MODULE_EXTENDED_INFO Extended) { Extended->ImageBase = Entry->ImageBase; Extended->ImageSize = Entry->ImageSize; IntCopyMemory( - Extended->FullPathName, Entry->path, sizeof(Extended->FullPathName)); + Extended->FullPathName, + Entry->path, + sizeof(Extended->FullPathName)); } NTSTATUS @@ -128,11 +131,11 @@ InitialiseDriverList() { PAGED_CODE(); - NTSTATUS status = STATUS_UNSUCCESSFUL; - SYSTEM_MODULES modules = {0}; - PDRIVER_LIST_ENTRY entry = NULL; + NTSTATUS status = STATUS_UNSUCCESSFUL; + SYSTEM_MODULES modules = {0}; + PDRIVER_LIST_ENTRY entry = NULL; PRTL_MODULE_EXTENDED_INFO module_entry = NULL; - PDRIVER_LIST_HEAD head = GetDriverList(); + PDRIVER_LIST_HEAD head = GetDriverList(); InterlockedExchange(&head->active, TRUE); InitializeListHead(&head->list_entry); @@ -140,7 +143,7 @@ InitialiseDriverList() KeInitializeGuardedMutex(&head->lock); head->can_hash_x86 = FALSE; - head->work_item = IoAllocateWorkItem(GetDriverDeviceObject()); + head->work_item = IoAllocateWorkItem(GetDriverDeviceObject()); if (!head->work_item) return STATUS_INSUFFICIENT_RESOURCES; @@ -156,30 +159,33 @@ InitialiseDriverList() /* skip hal.dll and ntoskrnl.exe */ for (UINT32 index = 2; index < modules.module_count; index++) { - entry = ImpExAllocatePool2(POOL_FLAG_NON_PAGED, - sizeof(DRIVER_LIST_ENTRY), - POOL_TAG_DRIVER_LIST); + entry = ImpExAllocatePool2( + POOL_FLAG_NON_PAGED, + sizeof(DRIVER_LIST_ENTRY), + POOL_TAG_DRIVER_LIST); if (!entry) continue; module_entry = &((PRTL_MODULE_EXTENDED_INFO)modules.address)[index]; - entry->hashed = TRUE; + entry->hashed = TRUE; entry->ImageBase = module_entry->ImageBase; entry->ImageSize = module_entry->ImageSize; - IntCopyMemory(entry->path, - module_entry->FullPathName, - sizeof(module_entry->FullPathName)); + IntCopyMemory( + entry->path, + module_entry->FullPathName, + sizeof(module_entry->FullPathName)); status = HashModule(module_entry, entry->text_hash); if (status == STATUS_INVALID_IMAGE_WIN_32) { - DEBUG_ERROR("32 bit module not hashed, will hash later. %x", - status); + DEBUG_ERROR( + "32 bit module not hashed, will hash later. %x", + status); entry->hashed = FALSE; - entry->x86 = TRUE; + entry->x86 = TRUE; InsertHeadList(&head->deferred_list, &entry->deferred_entry); } else if (!NT_SUCCESS(status)) { @@ -206,11 +212,11 @@ InitialiseDriverList() * think! */ VOID -FindDriverEntryByBaseAddress(_In_ PVOID ImageBase, - _Out_ PDRIVER_LIST_ENTRY* Entry) +FindDriverEntryByBaseAddress( + _In_ PVOID ImageBase, _Out_ PDRIVER_LIST_ENTRY* Entry) { - PDRIVER_LIST_HEAD head = GetDriverList(); - PLIST_ENTRY list_entry = NULL; + PDRIVER_LIST_HEAD head = GetDriverList(); + PLIST_ENTRY list_entry = NULL; PDRIVER_LIST_ENTRY driver_entry = NULL; ImpKeAcquireGuardedMutex(&head->lock); @@ -253,17 +259,17 @@ ProcessHashmapHashFunction(_In_ UINT64 Key) STATIC VOID -ImageLoadInsertNonSystemImageIntoProcessHashmap(_In_ PIMAGE_INFO ImageInfo, - _In_ HANDLE ProcessId, - _In_opt_ PUNICODE_STRING - FullImageName) +ImageLoadInsertNonSystemImageIntoProcessHashmap( + _In_ PIMAGE_INFO ImageInfo, + _In_ HANDLE ProcessId, + _In_opt_ PUNICODE_STRING FullImageName) { - INT32 index = 0; - NTSTATUS status = STATUS_UNSUCCESSFUL; - PEPROCESS process = NULL; - PRTL_HASHMAP map = GetProcessHashmap(); - PPROCESS_LIST_ENTRY entry = NULL; - PPROCESS_MAP_MODULE_ENTRY module = NULL; + INT32 index = 0; + NTSTATUS status = STATUS_UNSUCCESSFUL; + PEPROCESS process = NULL; + PRTL_HASHMAP map = GetProcessHashmap(); + PPROCESS_LIST_ENTRY entry = NULL; + PPROCESS_MAP_MODULE_ENTRY module = NULL; PPROCESS_MODULE_MAP_CONTEXT context = NULL; if (!map->active) @@ -288,7 +294,7 @@ ImageLoadInsertNonSystemImageIntoProcessHashmap(_In_ PIMAGE_INFO ImageInfo, } context = (PPROCESS_MODULE_MAP_CONTEXT)map->context; - module = ExAllocateFromLookasideListEx(&context->pool); + module = ExAllocateFromLookasideListEx(&context->pool); if (!module) goto end; @@ -303,7 +309,9 @@ ImageLoadInsertNonSystemImageIntoProcessHashmap(_In_ PIMAGE_INFO ImageInfo, */ if (FullImageName) UnicodeToCharBufString( - FullImageName, module->path, sizeof(module->path)); + FullImageName, + module->path, + sizeof(module->path)); InsertTailList(&entry->module_list, &module->entry); entry->list_count++; @@ -313,24 +321,27 @@ end: } VOID -ImageLoadNotifyRoutineCallback(_In_opt_ PUNICODE_STRING FullImageName, - _In_ HANDLE ProcessId, - _In_ PIMAGE_INFO ImageInfo) +ImageLoadNotifyRoutineCallback( + _In_opt_ PUNICODE_STRING FullImageName, + _In_ HANDLE ProcessId, + _In_ PIMAGE_INFO ImageInfo) { UNREFERENCED_PARAMETER(ProcessId); - NTSTATUS status = STATUS_UNSUCCESSFUL; - PDRIVER_LIST_ENTRY entry = NULL; - RTL_MODULE_EXTENDED_INFO module = {0}; - PDRIVER_LIST_HEAD head = GetDriverList(); - ANSI_STRING ansi_path = {0}; + NTSTATUS status = STATUS_UNSUCCESSFUL; + PDRIVER_LIST_ENTRY entry = NULL; + RTL_MODULE_EXTENDED_INFO module = {0}; + PDRIVER_LIST_HEAD head = GetDriverList(); + ANSI_STRING ansi_path = {0}; if (InterlockedExchange(&head->active, head->active) == FALSE) return; if (ImageInfo->SystemModeImage == FALSE) { ImageLoadInsertNonSystemImageIntoProcessHashmap( - ImageInfo, ProcessId, FullImageName); + ImageInfo, + ProcessId, + FullImageName); return; } @@ -341,13 +352,15 @@ ImageLoadNotifyRoutineCallback(_In_opt_ PUNICODE_STRING FullImageName, return; entry = ExAllocatePool2( - POOL_FLAG_NON_PAGED, sizeof(DRIVER_LIST_ENTRY), POOL_TAG_DRIVER_LIST); + POOL_FLAG_NON_PAGED, + sizeof(DRIVER_LIST_ENTRY), + POOL_TAG_DRIVER_LIST); if (!entry) return; - entry->hashed = TRUE; - entry->x86 = FALSE; + entry->hashed = TRUE; + entry->x86 = FALSE; entry->ImageBase = ImageInfo->ImageBase; entry->ImageSize = ImageInfo->ImageSize; @@ -356,9 +369,13 @@ ImageLoadNotifyRoutineCallback(_In_opt_ PUNICODE_STRING FullImageName, if (FullImageName) { UnicodeToCharBufString( - FullImageName, module.FullPathName, sizeof(module.FullPathName)); + FullImageName, + module.FullPathName, + sizeof(module.FullPathName)); IntCopyMemory( - entry->path, module.FullPathName, sizeof(module.FullPathName)); + entry->path, + module.FullPathName, + sizeof(module.FullPathName)); } DEBUG_VERBOSE("New system image ansi: %s", entry->path); @@ -368,7 +385,7 @@ hash: if (status == STATUS_INVALID_IMAGE_WIN_32) { DEBUG_ERROR("32 bit module not hashed, will hash later. %x", status); - entry->x86 = TRUE; + entry->x86 = TRUE; entry->hashed = FALSE; } else if (!NT_SUCCESS(status)) { @@ -383,18 +400,18 @@ hash: /* assumes map lock is held */ VOID -FreeProcessEntryModuleList(_In_ PPROCESS_LIST_ENTRY Entry, - _In_opt_ PVOID Context) +FreeProcessEntryModuleList( + _In_ PPROCESS_LIST_ENTRY Entry, _In_opt_ PVOID Context) { UNREFERENCED_PARAMETER(Context); - PRTL_HASHMAP map = GetProcessHashmap(); - PLIST_ENTRY list = NULL; - PPROCESS_MAP_MODULE_ENTRY list_entry = NULL; - PPROCESS_MODULE_MAP_CONTEXT context = map->context; + PRTL_HASHMAP map = GetProcessHashmap(); + PLIST_ENTRY list = NULL; + PPROCESS_MAP_MODULE_ENTRY list_entry = NULL; + PPROCESS_MODULE_MAP_CONTEXT context = map->context; while (!IsListEmpty(&Entry->module_list)) { - list = RemoveTailList(&Entry->module_list); + list = RemoveTailList(&Entry->module_list); list_entry = CONTAINING_RECORD(list, PROCESS_MAP_MODULE_ENTRY, entry); ExFreeToLookasideListEx(&context->pool, list_entry); @@ -402,15 +419,16 @@ FreeProcessEntryModuleList(_In_ PPROCESS_LIST_ENTRY Entry, } VOID -EnumerateProcessModuleList(_In_ HANDLE ProcessId, - _In_ PROCESS_MODULE_CALLBACK Callback, - _In_opt_ PVOID Context) +EnumerateProcessModuleList( + _In_ HANDLE ProcessId, + _In_ PROCESS_MODULE_CALLBACK Callback, + _In_opt_ PVOID Context) { - INT32 index = 0; - PRTL_HASHMAP map = GetProcessHashmap(); - BOOLEAN ret = FALSE; - PPROCESS_LIST_ENTRY entry = NULL; - PLIST_ENTRY list = NULL; + INT32 index = 0; + PRTL_HASHMAP map = GetProcessHashmap(); + BOOLEAN ret = FALSE; + PPROCESS_LIST_ENTRY entry = NULL; + PLIST_ENTRY list = NULL; PPROCESS_MAP_MODULE_ENTRY module = NULL; if (!map->active) @@ -439,15 +457,15 @@ end: } VOID -FindOurUserModeModuleEntry(_In_ PROCESS_MODULE_CALLBACK Callback, - _In_opt_ PVOID Context) +FindOurUserModeModuleEntry( + _In_ PROCESS_MODULE_CALLBACK Callback, _In_opt_ PVOID Context) { - INT32 index = 0; - PRTL_HASHMAP map = GetProcessHashmap(); - PPROCESS_LIST_ENTRY entry = NULL; - PACTIVE_SESSION session = GetActiveSession(); - PLIST_ENTRY list = NULL; - PPROCESS_MAP_MODULE_ENTRY module = NULL; + INT32 index = 0; + PRTL_HASHMAP map = GetProcessHashmap(); + PPROCESS_LIST_ENTRY entry = NULL; + PACTIVE_SESSION session = GetActiveSession(); + PLIST_ENTRY list = NULL; + PPROCESS_MAP_MODULE_ENTRY module = NULL; if (!map->active) return; @@ -480,10 +498,10 @@ end: VOID CleanupProcessHashmap() { - PRTL_HASHMAP map = GetProcessHashmap(); - PRTL_HASHMAP_ENTRY entry = NULL; - PRTL_HASHMAP_ENTRY temp = NULL; - PLIST_ENTRY list = NULL; + PRTL_HASHMAP map = GetProcessHashmap(); + PRTL_HASHMAP_ENTRY entry = NULL; + PRTL_HASHMAP_ENTRY temp = NULL; + PLIST_ENTRY list = NULL; PPROCESS_MODULE_MAP_CONTEXT context = NULL; RtlHashmapSetInactive(map); @@ -517,36 +535,39 @@ InitialiseProcessHashmap() { PAGED_CODE(); - NTSTATUS status = STATUS_UNSUCCESSFUL; + NTSTATUS status = STATUS_UNSUCCESSFUL; PPROCESS_MODULE_MAP_CONTEXT context = NULL; - context = ExAllocatePool2(POOL_FLAG_NON_PAGED, - sizeof(PROCESS_MODULE_MAP_CONTEXT), - POOL_TAG_HASHMAP); + context = ExAllocatePool2( + POOL_FLAG_NON_PAGED, + sizeof(PROCESS_MODULE_MAP_CONTEXT), + POOL_TAG_HASHMAP); if (!context) return STATUS_INSUFFICIENT_RESOURCES; - status = ExInitializeLookasideListEx(&context->pool, - NULL, - NULL, - NonPagedPoolNx, - 0, - sizeof(PROCESS_MAP_MODULE_ENTRY), - POOL_TAG_MODULE_LIST, - 0); + status = ExInitializeLookasideListEx( + &context->pool, + NULL, + NULL, + NonPagedPoolNx, + 0, + sizeof(PROCESS_MAP_MODULE_ENTRY), + POOL_TAG_MODULE_LIST, + 0); if (!NT_SUCCESS(status)) { ExFreePoolWithTag(context, POOL_TAG_HASHMAP); return status; } - status = RtlHashmapCreate(PROCESS_HASHMAP_BUCKET_COUNT, - sizeof(PROCESS_LIST_ENTRY), - ProcessHashmapHashFunction, - ProcessHashmapCompareFunction, - context, - GetProcessHashmap()); + status = RtlHashmapCreate( + PROCESS_HASHMAP_BUCKET_COUNT, + sizeof(PROCESS_LIST_ENTRY), + ProcessHashmapHashFunction, + ProcessHashmapCompareFunction, + context, + GetProcessHashmap()); if (!NT_SUCCESS(status)) { DEBUG_ERROR("RtlCreateHashmap: %lx", status); @@ -577,7 +598,7 @@ NTSTATUS InitialiseThreadList() { NTSTATUS status = STATUS_UNSUCCESSFUL; - PRB_TREE tree = GetThreadTree(); + PRB_TREE tree = GetThreadTree(); status = RtlRbTreeCreate(ThreadListTreeCompare, sizeof(THREAD_LIST_ENTRY), tree); @@ -590,8 +611,8 @@ InitialiseThreadList() } VOID -FindThreadListEntryByThreadAddress(_In_ HANDLE ThreadId, - _Out_ PTHREAD_LIST_ENTRY* Entry) +FindThreadListEntryByThreadAddress( + _In_ HANDLE ThreadId, _Out_ PTHREAD_LIST_ENTRY* Entry) { PRB_TREE tree = GetThreadTree(); RtlRbTreeAcquireLock(tree); @@ -604,8 +625,9 @@ STATIC BOOLEAN CanInitiateDeferredHashing(_In_ LPCSTR ProcessName, _In_ PDRIVER_LIST_HEAD Head) { - return !IntCompareString(ProcessName, "winlogon.exe") && Head->work_item ? TRUE - : FALSE; + return !IntCompareString(ProcessName, "winlogon.exe") && Head->work_item + ? TRUE + : FALSE; } STATIC @@ -613,7 +635,7 @@ VOID PrintHashmapCallback(_In_ PPROCESS_LIST_ENTRY Entry, _In_opt_ PVOID Context) { PPROCESS_MAP_MODULE_ENTRY module = NULL; - PLIST_ENTRY list = NULL; + PLIST_ENTRY list = NULL; UNREFERENCED_PARAMETER(Context); DEBUG_VERBOSE("Process ID: %p", Entry->process_id); @@ -621,10 +643,11 @@ PrintHashmapCallback(_In_ PPROCESS_LIST_ENTRY Entry, _In_opt_ PVOID Context) for (list = Entry->module_list.Flink; list != &Entry->module_list; list = list->Flink) { module = CONTAINING_RECORD(list, PROCESS_MAP_MODULE_ENTRY, entry); - DEBUG_VERBOSE(" -> Module Base: %p, size: %lx, path: %s", - (PVOID)module->base, - module->size, - module->path); + DEBUG_VERBOSE( + " -> Module Base: %p, size: %lx, path: %s", + (PVOID)module->base, + module->size, + module->path); } } @@ -635,17 +658,16 @@ EnumerateAndPrintProcessHashmap() } VOID -ProcessCreateNotifyRoutine(_In_ HANDLE ParentId, - _In_ HANDLE ProcessId, - _In_ BOOLEAN Create) +ProcessCreateNotifyRoutine( + _In_ HANDLE ParentId, _In_ HANDLE ProcessId, _In_ BOOLEAN Create) { - INT32 index = 0; - PKPROCESS parent = NULL; - PKPROCESS process = NULL; - PDRIVER_LIST_HEAD driver_list = GetDriverList(); - LPCSTR process_name = NULL; - PRTL_HASHMAP map = GetProcessHashmap(); - PPROCESS_LIST_ENTRY entry = NULL; + INT32 index = 0; + PKPROCESS parent = NULL; + PKPROCESS process = NULL; + PDRIVER_LIST_HEAD driver_list = GetDriverList(); + LPCSTR process_name = NULL; + PRTL_HASHMAP map = GetProcessHashmap(); + PPROCESS_LIST_ENTRY entry = NULL; if (!map->active) return; @@ -657,7 +679,7 @@ ProcessCreateNotifyRoutine(_In_ HANDLE ParentId, return; process_name = ImpPsGetProcessImageFileName(process); - index = RtlHashmapHashKeyAndAcquireBucket(map, ProcessId); + index = RtlHashmapHashKeyAndAcquireBucket(map, ProcessId); if (index == STATUS_INVALID_HASHMAP_INDEX) return; @@ -669,8 +691,8 @@ ProcessCreateNotifyRoutine(_In_ HANDLE ParentId, goto end; entry->process_id = ProcessId; - entry->process = process; - entry->parent = parent; + entry->process = process; + entry->parent = parent; InitializeListHead(&entry->module_list); @@ -681,10 +703,11 @@ ProcessCreateNotifyRoutine(_In_ HANDLE ParentId, * any x86 modules that werent hashed. */ if (CanInitiateDeferredHashing(process_name, driver_list)) { - IoQueueWorkItem(driver_list->work_item, - DeferredModuleHashingCallback, - NormalWorkQueue, - NULL); + IoQueueWorkItem( + driver_list->work_item, + DeferredModuleHashingCallback, + NormalWorkQueue, + NULL); } } else { @@ -707,14 +730,13 @@ end: } VOID -ThreadCreateNotifyRoutine(_In_ HANDLE ProcessId, - _In_ HANDLE ThreadId, - _In_ BOOLEAN Create) +ThreadCreateNotifyRoutine( + _In_ HANDLE ProcessId, _In_ HANDLE ThreadId, _In_ BOOLEAN Create) { - PTHREAD_LIST_ENTRY entry = NULL; - PKTHREAD thread = NULL; - PKPROCESS process = NULL; - PRB_TREE tree = GetThreadTree(); + PTHREAD_LIST_ENTRY entry = NULL; + PKTHREAD thread = NULL; + PKPROCESS process = NULL; + PRB_TREE tree = GetThreadTree(); /* ensure we don't insert new entries if we are unloading */ if (!tree->active) @@ -736,11 +758,11 @@ ThreadCreateNotifyRoutine(_In_ HANDLE ProcessId, if (!entry) goto end; - entry->thread_id = ThreadId; - entry->thread = thread; + entry->thread_id = ThreadId; + entry->thread = thread; entry->owning_process = process; - entry->apc = NULL; - entry->apc_queued = FALSE; + entry->apc = NULL; + entry->apc_queued = FALSE; } else { entry = RtlRbTreeFindNodeObject(tree, &ThreadId); @@ -759,9 +781,9 @@ end: } VOID -ObPostOpCallbackRoutine(_In_ PVOID RegistrationContext, - _In_ POB_POST_OPERATION_INFORMATION - OperationInformation) +ObPostOpCallbackRoutine( + _In_ PVOID RegistrationContext, + _In_ POB_POST_OPERATION_INFORMATION OperationInformation) { PAGED_CODE(); UNREFERENCED_PARAMETER(RegistrationContext); @@ -777,17 +799,19 @@ ObPostOpCallbackRoutine(_In_ PVOID RegistrationContext, #define DOWNGRADE_MSMPENG 3 CHAR PROCESS_HANDLE_OPEN_DOWNGRADE[PROCESS_HANDLE_OPEN_DOWNGRADE_COUNT] - [MAX_PROCESS_NAME_LENGTH] = {"lsass.exe", - "csrss.exe", - "WerFault.exe", - "MsMpEng.exe"}; + [MAX_PROCESS_NAME_LENGTH] = { + "lsass.exe", + "csrss.exe", + "WerFault.exe", + "MsMpEng.exe"}; #define PROCESS_HANDLE_OPEN_WHITELIST_COUNT 3 CHAR PROCESS_HANDLE_OPEN_WHITELIST[PROCESS_HANDLE_OPEN_WHITELIST_COUNT] - [MAX_PROCESS_NAME_LENGTH] = {"Discord.exe", - "svchost.exe", - "explorer.exe"}; + [MAX_PROCESS_NAME_LENGTH] = { + "Discord.exe", + "svchost.exe", + "explorer.exe"}; STATIC BOOLEAN @@ -795,7 +819,9 @@ IsWhitelistedHandleOpenProcess(_In_ LPCSTR ProcessName) { for (UINT32 index = 0; index < PROCESS_HANDLE_OPEN_WHITELIST_COUNT; index++) { - if (!IntCompareString(ProcessName, PROCESS_HANDLE_OPEN_WHITELIST[index])) + if (!IntCompareString( + ProcessName, + PROCESS_HANDLE_OPEN_WHITELIST[index])) return TRUE; } @@ -808,7 +834,9 @@ IsDowngradeHandleOpenProcess(_In_ LPCSTR ProcessName) { for (UINT32 index = 0; index < PROCESS_HANDLE_OPEN_DOWNGRADE_COUNT; index++) { - if (!IntCompareString(ProcessName, PROCESS_HANDLE_OPEN_DOWNGRADE[index])) + if (!IntCompareString( + ProcessName, + PROCESS_HANDLE_OPEN_DOWNGRADE[index])) return TRUE; } @@ -819,8 +847,9 @@ IsDowngradeHandleOpenProcess(_In_ LPCSTR ProcessName) #define GET_OBJECT_HEADER_FROM_HANDLE(x) ((x << 4) | 0xffff000000000000); OB_PREOP_CALLBACK_STATUS -ObPreOpCallbackRoutine(_In_ PVOID RegistrationContext, - _In_ POB_PRE_OPERATION_INFORMATION OperationInformation) +ObPreOpCallbackRoutine( + _In_ PVOID RegistrationContext, + _In_ POB_PRE_OPERATION_INFORMATION OperationInformation) { PAGED_CODE(); @@ -833,17 +862,17 @@ ObPreOpCallbackRoutine(_In_ PVOID RegistrationContext, * This callback routine is executed in the context of the thread that * is requesting to open said handle */ - NTSTATUS status = STATUS_UNSUCCESSFUL; - PEPROCESS process_creator = PsGetCurrentProcess(); - PEPROCESS protected_process = NULL; - PEPROCESS target_process = (PEPROCESS)OperationInformation->Object; - HANDLE process_creator_id = ImpPsGetProcessId(process_creator); - LONG protected_process_id = 0; - LPCSTR process_creator_name = NULL; - LPCSTR target_process_name = NULL; - LPCSTR protected_process_name = NULL; + NTSTATUS status = STATUS_UNSUCCESSFUL; + PEPROCESS process_creator = PsGetCurrentProcess(); + PEPROCESS protected_process = NULL; + PEPROCESS target_process = (PEPROCESS)OperationInformation->Object; + HANDLE process_creator_id = ImpPsGetProcessId(process_creator); + LONG protected_process_id = 0; + LPCSTR process_creator_name = NULL; + LPCSTR target_process_name = NULL; + LPCSTR protected_process_name = NULL; POB_CALLBACKS_CONFIG configuration = NULL; - UINT32 report_size = 0; + UINT32 report_size = 0; /* * This is to prevent the condition where the thread executing this @@ -863,8 +892,8 @@ ObPreOpCallbackRoutine(_In_ PVOID RegistrationContext, if (!protected_process_id || !protected_process) goto end; - process_creator_name = ImpPsGetProcessImageFileName(process_creator); - target_process_name = ImpPsGetProcessImageFileName(target_process); + process_creator_name = ImpPsGetProcessImageFileName(process_creator); + target_process_name = ImpPsGetProcessImageFileName(target_process); protected_process_name = ImpPsGetProcessImageFileName(protected_process); if (!protected_process_name || !target_process_name) @@ -910,7 +939,9 @@ ObPreOpCallbackRoutine(_In_ PVOID RegistrationContext, sizeof(OPEN_HANDLE_FAILURE_REPORT)); POPEN_HANDLE_FAILURE_REPORT report = ImpExAllocatePool2( - POOL_FLAG_NON_PAGED, report_size, REPORT_POOL_TAG); + POOL_FLAG_NON_PAGED, + report_size, + REPORT_POOL_TAG); if (!report) goto end; @@ -918,14 +949,15 @@ ObPreOpCallbackRoutine(_In_ PVOID RegistrationContext, INIT_REPORT_PACKET(report, REPORT_ILLEGAL_HANDLE_OPERATION, 0); report->is_kernel_handle = OperationInformation->KernelHandle; - report->process_id = process_creator_id; - report->thread_id = ImpPsGetCurrentThreadId(); - report->access = OperationInformation->Parameters + report->process_id = process_creator_id; + report->thread_id = ImpPsGetCurrentThreadId(); + report->access = OperationInformation->Parameters ->CreateHandleInformation.DesiredAccess; - IntCopyMemory(report->process_name, - process_creator_name, - HANDLE_REPORT_PROCESS_NAME_MAX_LENGTH); + IntCopyMemory( + report->process_name, + process_creator_name, + HANDLE_REPORT_PROCESS_NAME_MAX_LENGTH); status = CryptEncryptBuffer(report, report_size); @@ -946,8 +978,8 @@ end: /* stolen from ReactOS xD */ VOID NTAPI -ExUnlockHandleTableEntry(IN PHANDLE_TABLE HandleTable, - IN PHANDLE_TABLE_ENTRY HandleTableEntry) +ExUnlockHandleTableEntry( + IN PHANDLE_TABLE HandleTable, IN PHANDLE_TABLE_ENTRY HandleTableEntry) { INT64 old_value; PAGED_CODE(); @@ -971,43 +1003,46 @@ GetHandleAccessMask(_In_ PHANDLE_TABLE_ENTRY Entry) } static UNICODE_STRING OBJECT_TYPE_PROCESS = RTL_CONSTANT_STRING(L"Process"); -static UNICODE_STRING OBJECT_TYPE_THREAD = RTL_CONSTANT_STRING(L"Thread"); +static UNICODE_STRING OBJECT_TYPE_THREAD = RTL_CONSTANT_STRING(L"Thread"); STATIC BOOLEAN -EnumHandleCallback(_In_ PHANDLE_TABLE HandleTable, - _In_ PHANDLE_TABLE_ENTRY Entry, - _In_ HANDLE Handle, - _In_ PVOID Context) +EnumHandleCallback( + _In_ PHANDLE_TABLE HandleTable, + _In_ PHANDLE_TABLE_ENTRY Entry, + _In_ HANDLE Handle, + _In_ PVOID Context) { PAGED_CODE(); UNREFERENCED_PARAMETER(Context); - NTSTATUS status = STATUS_UNSUCCESSFUL; - PVOID object = NULL; - PVOID object_header = NULL; - POBJECT_TYPE object_type = NULL; - PEPROCESS process = NULL; - PEPROCESS protected_process = NULL; - LPCSTR process_name = NULL; - LPCSTR protected_process_name = NULL; - ACCESS_MASK handle_access_mask = 0; - UINT32 report_size = 0; + NTSTATUS status = STATUS_UNSUCCESSFUL; + PVOID object = NULL; + PVOID object_header = NULL; + POBJECT_TYPE object_type = NULL; + PEPROCESS process = NULL; + PEPROCESS protected_process = NULL; + LPCSTR process_name = NULL; + LPCSTR protected_process_name = NULL; + ACCESS_MASK handle_access_mask = 0; + UINT32 report_size = 0; object_header = GET_OBJECT_HEADER_FROM_HANDLE(Entry->ObjectPointerBits); /* Object header is the first 30 bytes of the object */ - object = (uintptr_t)object_header + OBJECT_HEADER_SIZE; + object = (uintptr_t)object_header + OBJECT_HEADER_SIZE; object_type = ImpObGetObjectType(object); /* TODO: check for threads aswell */ if (ImpRtlCompareUnicodeString( - &object_type->Name, &OBJECT_TYPE_PROCESS, TRUE)) { + &object_type->Name, + &OBJECT_TYPE_PROCESS, + TRUE)) { goto end; } - process = (PEPROCESS)object; + process = (PEPROCESS)object; process_name = ImpPsGetProcessImageFileName(process); SessionGetProcess(&protected_process); @@ -1114,13 +1149,14 @@ EnumHandleCallback(_In_ PHANDLE_TABLE HandleTable, INIT_REPORT_PACKET(report, REPORT_ILLEGAL_HANDLE_OPERATION, 0); report->is_kernel_handle = Entry->Attributes & OBJ_KERNEL_HANDLE; - report->process_id = ImpPsGetProcessId(process); - report->thread_id = 0; - report->access = handle_access_mask; + report->process_id = ImpPsGetProcessId(process); + report->thread_id = 0; + report->access = handle_access_mask; - IntCopyMemory(&report->process_name, - process_name, - HANDLE_REPORT_PROCESS_NAME_MAX_LENGTH); + IntCopyMemory( + &report->process_name, + process_name, + HANDLE_REPORT_PROCESS_NAME_MAX_LENGTH); status = CryptEncryptBuffer(report, report_size); @@ -1175,12 +1211,12 @@ EnumerateProcessHandles(_In_ PPROCESS_LIST_ENTRY Entry, _In_opt_ PVOID Context) STATIC VOID -TimerObjectValidateProcessModuleCallback(_In_ PPROCESS_MAP_MODULE_ENTRY Entry, - _In_opt_ PVOID Context) +TimerObjectValidateProcessModuleCallback( + _In_ PPROCESS_MAP_MODULE_ENTRY Entry, _In_opt_ PVOID Context) { - CHAR hash[SHA_256_HASH_LENGTH] = {0}; - NTSTATUS status = STATUS_UNSUCCESSFUL; - PACTIVE_SESSION session = (PACTIVE_SESSION)Context; + CHAR hash[SHA_256_HASH_LENGTH] = {0}; + NTSTATUS status = STATUS_UNSUCCESSFUL; + PACTIVE_SESSION session = (PACTIVE_SESSION)Context; if (!ARGUMENT_PRESENT(Context)) return; @@ -1203,13 +1239,13 @@ TimerObjectValidateProcessModuleCallback(_In_ PPROCESS_MAP_MODULE_ENTRY Entry, STATIC VOID -TimerObjectWorkItemRoutine(_In_ PDEVICE_OBJECT DeviceObject, - _In_opt_ PVOID Context) +TimerObjectWorkItemRoutine( + _In_ PDEVICE_OBJECT DeviceObject, _In_opt_ PVOID Context) { - NTSTATUS status = STATUS_UNSUCCESSFUL; - PTIMER_OBJECT timer = (PTIMER_OBJECT)Context; - PDRIVER_LIST_HEAD list = GetDriverList(); - PACTIVE_SESSION session = GetActiveSession(); + NTSTATUS status = STATUS_UNSUCCESSFUL; + PTIMER_OBJECT timer = (PTIMER_OBJECT)Context; + PDRIVER_LIST_HEAD list = GetDriverList(); + PACTIVE_SESSION session = GetActiveSession(); UNREFERENCED_PARAMETER(DeviceObject); @@ -1238,8 +1274,9 @@ TimerObjectWorkItemRoutine(_In_ PDEVICE_OBJECT DeviceObject, goto end; } - FindOurUserModeModuleEntry(TimerObjectValidateProcessModuleCallback, - session); + FindOurUserModeModuleEntry( + TimerObjectValidateProcessModuleCallback, + session); KeReleaseGuardedMutex(&session->lock); end: @@ -1251,10 +1288,11 @@ end: */ STATIC VOID -TimerObjectCallbackRoutine(_In_ PKDPC Dpc, - _In_opt_ PVOID DeferredContext, - _In_opt_ PVOID SystemArgument1, - _In_opt_ PVOID SystemArgument2) +TimerObjectCallbackRoutine( + _In_ PKDPC Dpc, + _In_opt_ PVOID DeferredContext, + _In_opt_ PVOID SystemArgument1, + _In_opt_ PVOID SystemArgument2) { UNREFERENCED_PARAMETER(Dpc); UNREFERENCED_PARAMETER(SystemArgument1); @@ -1272,10 +1310,11 @@ TimerObjectCallbackRoutine(_In_ PKDPC Dpc, /* we queue a work item because DPCs run at IRQL = DISPATCH_LEVEL and we * need certain routines which cannot be run at an IRQL this high.*/ InterlockedExchange(&timer->state, TRUE); - IoQueueWorkItem(timer->work_item, - TimerObjectWorkItemRoutine, - BackgroundWorkQueue, - timer); + IoQueueWorkItem( + timer->work_item, + TimerObjectWorkItemRoutine, + BackgroundWorkQueue, + timer); } NTSTATUS @@ -1335,9 +1374,9 @@ RegisterProcessObCallbacks() { PAGED_CODE(); - NTSTATUS status = STATUS_UNSUCCESSFUL; - PACTIVE_SESSION config = GetActiveSession(); - OB_CALLBACK_REGISTRATION callback_registration = {0}; + NTSTATUS status = STATUS_UNSUCCESSFUL; + PACTIVE_SESSION config = GetActiveSession(); + OB_CALLBACK_REGISTRATION callback_registration = {0}; OB_OPERATION_REGISTRATION operation_registration = {0}; DEBUG_VERBOSE("Enabling ObRegisterCallbacks."); @@ -1346,13 +1385,13 @@ RegisterProcessObCallbacks() operation_registration.ObjectType = PsProcessType; operation_registration.Operations |= OB_OPERATION_HANDLE_CREATE; operation_registration.Operations |= OB_OPERATION_HANDLE_DUPLICATE; - operation_registration.PreOperation = ObPreOpCallbackRoutine; + operation_registration.PreOperation = ObPreOpCallbackRoutine; operation_registration.PostOperation = ObPostOpCallbackRoutine; - callback_registration.Version = OB_FLT_REGISTRATION_VERSION; + callback_registration.Version = OB_FLT_REGISTRATION_VERSION; callback_registration.OperationRegistration = &operation_registration; callback_registration.OperationRegistrationCount = 1; - callback_registration.RegistrationContext = NULL; + callback_registration.RegistrationContext = NULL; status = ImpObRegisterCallbacks( &callback_registration, diff --git a/driver/containers/map.c b/driver/containers/map.c index 042628c..b1d3fe0 100644 --- a/driver/containers/map.c +++ b/driver/containers/map.c @@ -11,29 +11,33 @@ RtlHashmapDelete(_In_ PRTL_HASHMAP Hashmap) } NTSTATUS -RtlHashmapCreate(_In_ UINT32 BucketCount, - _In_ UINT32 EntryObjectSize, - _In_ HASH_FUNCTION HashFunction, - _In_ COMPARE_FUNCTION CompareFunction, - _In_opt_ PVOID Context, - _Out_ PRTL_HASHMAP Hashmap) +RtlHashmapCreate( + _In_ UINT32 BucketCount, + _In_ UINT32 EntryObjectSize, + _In_ HASH_FUNCTION HashFunction, + _In_ COMPARE_FUNCTION CompareFunction, + _In_opt_ PVOID Context, + _Out_ PRTL_HASHMAP Hashmap) { - NTSTATUS status = STATUS_UNSUCCESSFUL; - UINT32 entry_size = sizeof(RTL_HASHMAP_ENTRY) + EntryObjectSize; - PRTL_HASHMAP_ENTRY entry = NULL; + NTSTATUS status = STATUS_UNSUCCESSFUL; + UINT32 entry_size = sizeof(RTL_HASHMAP_ENTRY) + EntryObjectSize; + PRTL_HASHMAP_ENTRY entry = NULL; if (!CompareFunction || !HashFunction) return STATUS_INVALID_PARAMETER; Hashmap->buckets = ExAllocatePool2( - POOL_FLAG_NON_PAGED, BucketCount * entry_size, POOL_TAG_HASHMAP); + POOL_FLAG_NON_PAGED, + BucketCount * entry_size, + POOL_TAG_HASHMAP); if (!Hashmap->buckets) return STATUS_INSUFFICIENT_RESOURCES; - Hashmap->locks = ExAllocatePool2(POOL_FLAG_NON_PAGED, - sizeof(KGUARDED_MUTEX) * BucketCount, - POOL_TAG_HASHMAP); + Hashmap->locks = ExAllocatePool2( + POOL_FLAG_NON_PAGED, + sizeof(KGUARDED_MUTEX) * BucketCount, + POOL_TAG_HASHMAP); if (!Hashmap->locks) { ExFreePoolWithTag(Hashmap->buckets, POOL_TAG_HASHMAP); @@ -41,20 +45,21 @@ RtlHashmapCreate(_In_ UINT32 BucketCount, } for (UINT32 index = 0; index < BucketCount; index++) { - entry = &Hashmap->buckets[index]; + entry = &Hashmap->buckets[index]; entry->in_use = FALSE; InitializeListHead(&entry->entry); KeInitializeGuardedMutex(&Hashmap->locks[index]); } - status = ExInitializeLookasideListEx(&Hashmap->pool, - NULL, - NULL, - NonPagedPoolNx, - 0, - entry_size, - POOL_TAG_HASHMAP, - 0); + status = ExInitializeLookasideListEx( + &Hashmap->pool, + NULL, + NULL, + NonPagedPoolNx, + 0, + entry_size, + POOL_TAG_HASHMAP, + 0); if (!NT_SUCCESS(status)) { DEBUG_ERROR("ExInitializeLookasideListEx: %x", status); @@ -63,12 +68,12 @@ RtlHashmapCreate(_In_ UINT32 BucketCount, return status; } - Hashmap->bucket_count = BucketCount; - Hashmap->hash_function = HashFunction; + Hashmap->bucket_count = BucketCount; + Hashmap->hash_function = HashFunction; Hashmap->compare_function = CompareFunction; - Hashmap->object_size = EntryObjectSize; - Hashmap->active = TRUE; - Hashmap->context = Context; + Hashmap->object_size = EntryObjectSize; + Hashmap->active = TRUE; + Hashmap->context = Context; return STATUS_SUCCESS; } @@ -78,8 +83,8 @@ STATIC PRTL_HASHMAP_ENTRY RtlpHashmapFindUnusedEntry(_In_ PLIST_ENTRY Head) { - PRTL_HASHMAP_ENTRY entry = NULL; - PLIST_ENTRY list_entry = Head->Flink; + PRTL_HASHMAP_ENTRY entry = NULL; + PLIST_ENTRY list_entry = Head->Flink; while (list_entry != Head) { entry = CONTAINING_RECORD(list_entry, RTL_HASHMAP_ENTRY, entry); @@ -141,16 +146,16 @@ RtlHashmapReleaseBucket(_Inout_ PRTL_HASHMAP Hashmap, _In_ UINT32 Index) PVOID RtlHashmapEntryInsert(_In_ PRTL_HASHMAP Hashmap, _In_ UINT32 Index) { - UINT32 index = 0; - PLIST_ENTRY list_head = NULL; - PRTL_HASHMAP_ENTRY entry = NULL; + UINT32 index = 0; + PLIST_ENTRY list_head = NULL; + PRTL_HASHMAP_ENTRY entry = NULL; PRTL_HASHMAP_ENTRY new_entry = NULL; if (!Hashmap->active) return NULL; list_head = &(&Hashmap->buckets[index])->entry; - entry = RtlpHashmapFindUnusedEntry(list_head); + entry = RtlpHashmapFindUnusedEntry(list_head); if (entry) return entry; @@ -172,11 +177,10 @@ RtlHashmapEntryInsert(_In_ PRTL_HASHMAP Hashmap, _In_ UINT32 Index) * Also assumes lock is held. */ PVOID -RtlHashmapEntryLookup(_In_ PRTL_HASHMAP Hashmap, - _In_ UINT32 Index, - _In_ PVOID Compare) +RtlHashmapEntryLookup( + _In_ PRTL_HASHMAP Hashmap, _In_ UINT32 Index, _In_ PVOID Compare) { - UINT32 index = 0; + UINT32 index = 0; PRTL_HASHMAP_ENTRY entry = NULL; if (!Hashmap->active) @@ -201,19 +205,18 @@ RtlHashmapEntryLookup(_In_ PRTL_HASHMAP Hashmap, /* Assumes lock is held */ BOOLEAN -RtlHashmapEntryDelete(_Inout_ PRTL_HASHMAP Hashmap, - _In_ UINT32 Index, - _In_ PVOID Compare) +RtlHashmapEntryDelete( + _Inout_ PRTL_HASHMAP Hashmap, _In_ UINT32 Index, _In_ PVOID Compare) { - UINT32 index = 0; - PLIST_ENTRY list_head = NULL; - PLIST_ENTRY list_entry = NULL; - PRTL_HASHMAP_ENTRY entry = NULL; + UINT32 index = 0; + PLIST_ENTRY list_head = NULL; + PLIST_ENTRY list_entry = NULL; + PRTL_HASHMAP_ENTRY entry = NULL; if (!Hashmap->active) return FALSE; - list_head = &(&Hashmap->buckets[index])->entry; + list_head = &(&Hashmap->buckets[index])->entry; list_entry = list_head->Flink; while (list_entry != list_head) { @@ -240,18 +243,19 @@ RtlHashmapEntryDelete(_Inout_ PRTL_HASHMAP Hashmap, /* assumes lock is held */ VOID -RtlHashmapEnumerate(_In_ PRTL_HASHMAP Hashmap, - _In_ ENUMERATE_HASHMAP EnumerationCallback, - _In_opt_ PVOID Context) +RtlHashmapEnumerate( + _In_ PRTL_HASHMAP Hashmap, + _In_ ENUMERATE_HASHMAP EnumerationCallback, + _In_opt_ PVOID Context) { - PLIST_ENTRY list_head = NULL; - PLIST_ENTRY list_entry = NULL; - PRTL_HASHMAP_ENTRY entry = NULL; + PLIST_ENTRY list_head = NULL; + PLIST_ENTRY list_entry = NULL; + PRTL_HASHMAP_ENTRY entry = NULL; for (UINT32 index = 0; index < Hashmap->bucket_count; index++) { KeAcquireGuardedMutex(&Hashmap->locks[index]); - list_head = &Hashmap->buckets[index]; + list_head = &Hashmap->buckets[index]; list_entry = list_head->Flink; while (list_entry != list_head) { diff --git a/driver/containers/tree.c b/driver/containers/tree.c index 2845a9a..3e0439a 100644 --- a/driver/containers/tree.c +++ b/driver/containers/tree.c @@ -108,9 +108,9 @@ RtlRbTreePrintCurrentStatistics(_In_ PRB_TREE Tree) * - This stores the size of the objects that will be stored in the tree. It * is used to allocate memory for the nodes. * - Lets say each node needs to have a THREAD_LIST_ENTRY object. The - * ObjectSize = sizeof(THREAD_LIST_OBJECT) and in turn will mean each node will - * be of size: sizeof(THREAD_LIST_OBJECT) + sizeof(RB_TREE_NODE). This is also - * this size the lookaside list pools will be set to. + * ObjectSize = sizeof(THREAD_LIST_OBJECT) and in turn will mean each node + * will be of size: sizeof(THREAD_LIST_OBJECT) + sizeof(RB_TREE_NODE). This is + * also this size the lookaside list pools will be set to. * * > `LOOKASIDE_LIST_EX pool`: * - This is a lookaside list that provides a fast, efficient way to allocate @@ -118,31 +118,31 @@ RtlRbTreePrintCurrentStatistics(_In_ PRB_TREE Tree) * block is `ObjectSize + sizeof(RB_TREE_NODE)`. */ NTSTATUS -RtlRbTreeCreate(_In_ RB_COMPARE Compare, - _In_ UINT32 ObjectSize, - _Out_ PRB_TREE Tree) +RtlRbTreeCreate( + _In_ RB_COMPARE Compare, _In_ UINT32 ObjectSize, _Out_ PRB_TREE Tree) { NTSTATUS status = STATUS_UNSUCCESSFUL; if (!ARGUMENT_PRESENT(Compare) || ObjectSize == 0) return STATUS_INVALID_PARAMETER; - status = ExInitializeLookasideListEx(&Tree->pool, - NULL, - NULL, - NonPagedPoolNx, - 0, - ObjectSize + sizeof(RB_TREE_NODE), - POOL_TAG_RB_TREE, - 0); + status = ExInitializeLookasideListEx( + &Tree->pool, + NULL, + NULL, + NonPagedPoolNx, + 0, + ObjectSize + sizeof(RB_TREE_NODE), + POOL_TAG_RB_TREE, + 0); if (!NT_SUCCESS(status)) return status; - Tree->compare = Compare; - Tree->deletion_count = 0; + Tree->compare = Compare; + Tree->deletion_count = 0; Tree->insertion_count = 0; - Tree->node_count = 0; + Tree->node_count = 0; KeInitializeGuardedMutex(&Tree->lock); @@ -167,7 +167,7 @@ VOID RtlpRbTreeRotateLeft(_In_ PRB_TREE Tree, _In_ PRB_TREE_NODE Node) { PRB_TREE_NODE right_child = Node->right; - Node->right = right_child->left; + Node->right = right_child->left; if (right_child->left) right_child->left->parent = Node; @@ -182,7 +182,7 @@ RtlpRbTreeRotateLeft(_In_ PRB_TREE Tree, _In_ PRB_TREE_NODE Node) Node->parent->right = right_child; right_child->left = Node; - Node->parent = right_child; + Node->parent = right_child; } /* @@ -205,7 +205,7 @@ VOID RtlpRbTreeRotateRight(_In_ PRB_TREE Tree, _In_ PRB_TREE_NODE Node) { PRB_TREE_NODE left_child = Node->left; - Node->left = left_child->right; + Node->left = left_child->right; if (left_child->right) left_child->right->parent = Node; @@ -220,7 +220,7 @@ RtlpRbTreeRotateRight(_In_ PRB_TREE Tree, _In_ PRB_TREE_NODE Node) Node->parent->left = left_child; left_child->right = Node; - Node->parent = left_child; + Node->parent = left_child; } /* @@ -241,8 +241,8 @@ STATIC VOID RtlpRbTreeFixupInsert(_In_ PRB_TREE Tree, _In_ PRB_TREE_NODE Node) { - PRB_TREE_NODE uncle = NULL; - PRB_TREE_NODE parent = NULL; + PRB_TREE_NODE uncle = NULL; + PRB_TREE_NODE parent = NULL; PRB_TREE_NODE grandparent = NULL; while ((parent = Node->parent) && parent->colour == red) { @@ -252,19 +252,19 @@ RtlpRbTreeFixupInsert(_In_ PRB_TREE Tree, _In_ PRB_TREE_NODE Node) uncle = grandparent->right; if (uncle && uncle->colour == red) { - parent->colour = black; - uncle->colour = black; + parent->colour = black; + uncle->colour = black; grandparent->colour = red; - Node = grandparent; + Node = grandparent; } else { if (Node == parent->right) { RtlpRbTreeRotateLeft(Tree, parent); - Node = parent; + Node = parent; parent = Node->parent; } - parent->colour = black; + parent->colour = black; grandparent->colour = red; RtlpRbTreeRotateRight(Tree, grandparent); } @@ -273,19 +273,19 @@ RtlpRbTreeFixupInsert(_In_ PRB_TREE Tree, _In_ PRB_TREE_NODE Node) uncle = grandparent->left; if (uncle && uncle->colour == red) { - parent->colour = black; - uncle->colour = black; + parent->colour = black; + uncle->colour = black; grandparent->colour = red; - Node = grandparent; + Node = grandparent; } else { if (Node == parent->left) { RtlpRbTreeRotateRight(Tree, parent); - Node = parent; + Node = parent; parent = Node->parent; } - parent->colour = black; + parent->colour = black; grandparent->colour = red; RtlpRbTreeRotateLeft(Tree, grandparent); } @@ -325,9 +325,9 @@ RtlpRbTreeFixupInsert(_In_ PRB_TREE Tree, _In_ PRB_TREE_NODE Node) PVOID RtlRbTreeInsertNode(_In_ PRB_TREE Tree, _In_ PVOID Key) { - UINT32 result = 0; - PRB_TREE_NODE node = NULL; - PRB_TREE_NODE parent = NULL; + UINT32 result = 0; + PRB_TREE_NODE node = NULL; + PRB_TREE_NODE parent = NULL; PRB_TREE_NODE current = NULL; node = ExAllocateFromLookasideListEx(&Tree->pool); @@ -336,8 +336,8 @@ RtlRbTreeInsertNode(_In_ PRB_TREE Tree, _In_ PVOID Key) return NULL; node->parent = NULL; - node->left = NULL; - node->right = NULL; + node->left = NULL; + node->right = NULL; node->colour = red; current = Tree->root; @@ -437,7 +437,7 @@ RtlpRbTreeFixupDelete(_In_ PRB_TREE Tree, _In_ PRB_TREE_NODE Node) sibling = Node->parent->right; if (sibling && sibling->colour == red) { - sibling->colour = black; + sibling->colour = black; Node->parent->colour = red; RtlpRbTreeRotateLeft(Tree, Node->parent); sibling = Node->parent->right; @@ -446,7 +446,7 @@ RtlpRbTreeFixupDelete(_In_ PRB_TREE Tree, _In_ PRB_TREE_NODE Node) if (sibling && (!sibling->left || sibling->left->colour == black) && (!sibling->right || sibling->right->colour == black)) { sibling->colour = red; - Node = Node->parent; + Node = Node->parent; } else { if (sibling && @@ -460,7 +460,7 @@ RtlpRbTreeFixupDelete(_In_ PRB_TREE Tree, _In_ PRB_TREE_NODE Node) } if (sibling) { - sibling->colour = Node->parent->colour; + sibling->colour = Node->parent->colour; Node->parent->colour = black; if (sibling->right) @@ -476,7 +476,7 @@ RtlpRbTreeFixupDelete(_In_ PRB_TREE Tree, _In_ PRB_TREE_NODE Node) sibling = Node->parent->left; if (sibling && sibling->colour == red) { - sibling->colour = black; + sibling->colour = black; Node->parent->colour = red; RtlpRbTreeRotateRight(Tree, Node->parent); sibling = Node->parent->left; @@ -486,7 +486,7 @@ RtlpRbTreeFixupDelete(_In_ PRB_TREE Tree, _In_ PRB_TREE_NODE Node) (!sibling->right || sibling->right->colour == black) && (!sibling->left || sibling->left->colour == black)) { sibling->colour = red; - Node = Node->parent; + Node = Node->parent; } else { if (sibling && @@ -500,7 +500,7 @@ RtlpRbTreeFixupDelete(_In_ PRB_TREE Tree, _In_ PRB_TREE_NODE Node) } if (sibling) { - sibling->colour = Node->parent->colour; + sibling->colour = Node->parent->colour; Node->parent->colour = black; if (sibling->left) @@ -538,9 +538,10 @@ RtlpRbTreeFixupDelete(_In_ PRB_TREE Tree, _In_ PRB_TREE_NODE Node) */ STATIC VOID -RtlpRbTreeTransplant(_In_ PRB_TREE Tree, - _In_ PRB_TREE_NODE Target, - _In_ PRB_TREE_NODE Replacement) +RtlpRbTreeTransplant( + _In_ PRB_TREE Tree, + _In_ PRB_TREE_NODE Target, + _In_ PRB_TREE_NODE Replacement) { if (!Target->parent) Tree->root = Replacement; @@ -557,7 +558,7 @@ STATIC PRB_TREE_NODE RtlpRbTreeFindNode(_In_ PRB_TREE Tree, _In_ PVOID Key) { - INT32 result = 0; + INT32 result = 0; PRB_TREE_NODE current = Tree->root; while (current) { @@ -597,10 +598,10 @@ RtlpRbTreeFindNode(_In_ PRB_TREE Tree, _In_ PVOID Key) VOID RtlRbTreeDeleteNode(_In_ PRB_TREE Tree, _In_ PVOID Key) { - PRB_TREE_NODE target = NULL; - PRB_TREE_NODE child = NULL; + PRB_TREE_NODE target = NULL; + PRB_TREE_NODE child = NULL; PRB_TREE_NODE successor = NULL; - COLOUR colour = {0}; + COLOUR colour = {0}; /* We want the node not the object */ target = RtlpRbTreeFindNode(Tree, Key); @@ -620,8 +621,8 @@ RtlRbTreeDeleteNode(_In_ PRB_TREE Tree, _In_ PVOID Key) } else { successor = RtlpRbTreeMinimum(target->right); - colour = successor->colour; - child = successor->right; + colour = successor->colour; + child = successor->right; if (successor->parent == target) { if (child) @@ -629,14 +630,14 @@ RtlRbTreeDeleteNode(_In_ PRB_TREE Tree, _In_ PVOID Key) } else { RtlpRbTreeTransplant(Tree, successor, successor->right); - successor->right = target->right; + successor->right = target->right; successor->right->parent = successor; } RtlpRbTreeTransplant(Tree, target, successor); - successor->left = target->left; + successor->left = target->left; successor->left->parent = successor; - successor->colour = target->colour; + successor->colour = target->colour; } if (colour == black && child) @@ -654,7 +655,7 @@ RtlRbTreeDeleteNode(_In_ PRB_TREE Tree, _In_ PVOID Key) PVOID RtlRbTreeFindNodeObject(_In_ PRB_TREE Tree, _In_ PVOID Key) { - INT32 result = 0; + INT32 result = 0; PRB_TREE_NODE current = Tree->root; while (current) { @@ -673,9 +674,10 @@ RtlRbTreeFindNodeObject(_In_ PRB_TREE Tree, _In_ PVOID Key) STATIC VOID -RtlpRbTreeEnumerate(_In_ PRB_TREE_NODE Node, - _In_ RB_ENUM_CALLBACK Callback, - _In_opt_ PVOID Context) +RtlpRbTreeEnumerate( + _In_ PRB_TREE_NODE Node, + _In_ RB_ENUM_CALLBACK Callback, + _In_opt_ PVOID Context) { if (Node == NULL) return; @@ -686,9 +688,8 @@ RtlpRbTreeEnumerate(_In_ PRB_TREE_NODE Node, } VOID -RtlRbTreeEnumerate(_In_ PRB_TREE Tree, - _In_ RB_ENUM_CALLBACK Callback, - _In_opt_ PVOID Context) +RtlRbTreeEnumerate( + _In_ PRB_TREE Tree, _In_ RB_ENUM_CALLBACK Callback, _In_opt_ PVOID Context) { if (Tree->root == NULL) return; @@ -708,11 +709,12 @@ RtlpPrintInOrder(PRB_TREE_NODE Node) RtlpPrintInOrder(Node->left); const char* color = (Node->colour == red) ? "Red" : "Black"; - DbgPrintEx(DPFLTR_DEFAULT_ID, - DPFLTR_INFO_LEVEL, - "Node: Key=%p, Color=%s\n", - *((PHANDLE)Node->object), - color); + DbgPrintEx( + DPFLTR_DEFAULT_ID, + DPFLTR_INFO_LEVEL, + "Node: Key=%p, Color=%s\n", + *((PHANDLE)Node->object), + color); RtlpPrintInOrder(Node->right); } @@ -722,7 +724,7 @@ RtlRbTreeInOrderPrint(_In_ PRB_TREE Tree) { DEBUG_ERROR("*************************************************"); DEBUG_ERROR("<><><><>STARTING IN ORDER PRINT <><><><><><"); - RtlRbTreeAcquireLock(Tree); + RtlRbTreeAcquireLock(Tree); RtlpPrintInOrder(Tree->root); RtlRbTreeReleaselock(Tree); DEBUG_ERROR("<><><><>ENDING IN ORDER PRINT <><><><><><"); diff --git a/driver/crypt.c b/driver/crypt.c index 38884c8..2228497 100644 --- a/driver/crypt.c +++ b/driver/crypt.c @@ -1,8 +1,8 @@ #include "crypt.h" +#include "driver.h" #include "imports.h" #include "session.h" -#include "driver.h" #include "util.h" #include "types/tpm20.h" @@ -10,8 +10,8 @@ #include "lib/stdlib.h" -#include #include +#include FORCEINLINE STATIC @@ -25,7 +25,7 @@ STATIC __m256i CryptXorKeyGenerate_m256i() { - UINT32 seed = (UINT32)__rdtsc(); + UINT32 seed = (UINT32)__rdtsc(); UINT64 key_1 = CryptGenerateRandomKey64(&seed); UINT64 key_2 = CryptGenerateRandomKey64(&seed); UINT64 key_3 = CryptGenerateRandomKey64(&seed); @@ -45,8 +45,8 @@ VOID CryptEncryptImportsArray(_In_ PUINT64 Array, _In_ UINT32 Entries) { __m256i* imports_key = GetDriverImportsKey(); - UINT32 block_size = sizeof(__m256i) / sizeof(UINT64); - UINT32 block_count = Entries / block_size; + UINT32 block_size = sizeof(__m256i) / sizeof(UINT64); + UINT32 block_count = Entries / block_size; *imports_key = CryptXorKeyGenerate_m256i(); @@ -57,19 +57,21 @@ CryptEncryptImportsArray(_In_ PUINT64 Array, _In_ UINT32 Entries) */ for (UINT32 block_index = 0; block_index < block_count; block_index++) { __m256i current_block = {0}; - __m256i load_block = {0}; - __m256i xored_block = {0}; + __m256i load_block = {0}; + __m256i xored_block = {0}; - IntCopyMemory(¤t_block, - &Array[block_index * block_size], - sizeof(__m256i)); + IntCopyMemory( + ¤t_block, + &Array[block_index * block_size], + sizeof(__m256i)); - load_block = _mm256_loadu_si256(¤t_block); + load_block = _mm256_loadu_si256(¤t_block); xored_block = _mm256_xor_si256(load_block, *imports_key); - IntCopyMemory(&Array[block_index * block_size], - &xored_block, - sizeof(__m256i)); + IntCopyMemory( + &Array[block_index * block_size], + &xored_block, + sizeof(__m256i)); } } @@ -78,13 +80,14 @@ INLINE __m256i CryptDecryptImportBlock(_In_ PUINT64 Array, _In_ UINT32 BlockIndex) { - __m256i load_block = {0}; + __m256i load_block = {0}; __m256i* imports_key = GetDriverImportsKey(); - UINT32 block_size = sizeof(__m256i) / sizeof(UINT64); + UINT32 block_size = sizeof(__m256i) / sizeof(UINT64); - IntCopyMemory(&load_block, - &Array[BlockIndex * block_size], - sizeof(__m256i)); + IntCopyMemory( + &load_block, + &Array[BlockIndex * block_size], + sizeof(__m256i)); return _mm256_xor_si256(load_block, *imports_key); } @@ -92,23 +95,24 @@ CryptDecryptImportBlock(_In_ PUINT64 Array, _In_ UINT32 BlockIndex) FORCEINLINE INLINE VOID -CryptFindContainingBlockForArrayIndex(_In_ UINT32 EntryIndex, - _In_ UINT32 BlockSize, - _Out_ PUINT32 ContainingBlockIndex, - _Out_ PUINT32 BlockSubIndex) +CryptFindContainingBlockForArrayIndex( + _In_ UINT32 EntryIndex, + _In_ UINT32 BlockSize, + _Out_ PUINT32 ContainingBlockIndex, + _Out_ PUINT32 BlockSubIndex) { UINT32 containing_block = EntryIndex; - UINT32 block_index = 0; + UINT32 block_index = 0; if (EntryIndex < BlockSize) { *ContainingBlockIndex = 0; - *BlockSubIndex = EntryIndex; + *BlockSubIndex = EntryIndex; return; } if (EntryIndex == BlockSize) { *ContainingBlockIndex = 1; - *BlockSubIndex = 0; + *BlockSubIndex = 0; return; } @@ -118,25 +122,25 @@ CryptFindContainingBlockForArrayIndex(_In_ UINT32 EntryIndex, } *ContainingBlockIndex = containing_block / BlockSize; - *BlockSubIndex = block_index; + *BlockSubIndex = block_index; } UINT64 -CryptDecryptImportsArrayEntry(_In_ PUINT64 Array, - _In_ UINT32 Entries, - _In_ UINT32 EntryIndex) +CryptDecryptImportsArrayEntry( + _In_ PUINT64 Array, _In_ UINT32 Entries, _In_ UINT32 EntryIndex) { - __m256i original_block = {0}; - __m128i original_half = {0}; - UINT32 block_size = sizeof(__m256i) / sizeof(UINT64); - UINT32 containing_block_index = 0; - UINT32 block_sub_index = 0; - UINT64 pointer = 0; + __m256i original_block = {0}; + __m128i original_half = {0}; + UINT32 block_size = sizeof(__m256i) / sizeof(UINT64); + UINT32 containing_block_index = 0; + UINT32 block_sub_index = 0; + UINT64 pointer = 0; - CryptFindContainingBlockForArrayIndex(EntryIndex, - block_size, - &containing_block_index, - &block_sub_index); + CryptFindContainingBlockForArrayIndex( + EntryIndex, + block_size, + &containing_block_index, + &block_sub_index); original_block = CryptDecryptImportBlock(Array, containing_block_index); @@ -164,21 +168,22 @@ STATIC PBCRYPT_KEY_DATA_BLOB_HEADER CryptBuildBlobForKeyImport(_In_ PACTIVE_SESSION Session) { - PBCRYPT_KEY_DATA_BLOB_HEADER blob = - ExAllocatePool2(POOL_FLAG_NON_PAGED, - sizeof(BCRYPT_KEY_DATA_BLOB_HEADER) + AES_256_KEY_SIZE, - POOL_TAG_CRYPT); + PBCRYPT_KEY_DATA_BLOB_HEADER blob = ExAllocatePool2( + POOL_FLAG_NON_PAGED, + sizeof(BCRYPT_KEY_DATA_BLOB_HEADER) + AES_256_KEY_SIZE, + POOL_TAG_CRYPT); if (!blob) return NULL; - blob->dwMagic = BCRYPT_KEY_DATA_BLOB_MAGIC; + blob->dwMagic = BCRYPT_KEY_DATA_BLOB_MAGIC; blob->dwVersion = BCRYPT_KEY_DATA_BLOB_VERSION1; blob->cbKeyData = AES_256_KEY_SIZE; - IntCopyMemory((UINT64)blob + sizeof(BCRYPT_KEY_DATA_BLOB_HEADER), - Session->aes_key, - AES_256_KEY_SIZE); + IntCopyMemory( + (UINT64)blob + sizeof(BCRYPT_KEY_DATA_BLOB_HEADER), + Session->aes_key, + AES_256_KEY_SIZE); return blob; } @@ -211,12 +216,12 @@ CryptRequestRequiredBufferLength(_In_ UINT32 BufferLength) NTSTATUS CryptEncryptBuffer(_In_ PVOID Buffer, _In_ UINT32 BufferLength) { - NTSTATUS status = STATUS_UNSUCCESSFUL; - UINT32 data_copied = 0; - PACTIVE_SESSION session = GetActiveSession(); - UCHAR local_iv[sizeof(session->iv)] = {0}; - UINT64 buffer = (UINT64)Buffer; - UINT32 length = BufferLength; + NTSTATUS status = STATUS_UNSUCCESSFUL; + UINT32 data_copied = 0; + PACTIVE_SESSION session = GetActiveSession(); + UCHAR local_iv[sizeof(session->iv)] = {0}; + UINT64 buffer = (UINT64)Buffer; + UINT32 length = BufferLength; /* The IV is consumed during every encrypt / decrypt procedure, so to ensure * we have access to the iv we need to create a local copy.*/ @@ -226,16 +231,17 @@ CryptEncryptBuffer(_In_ PVOID Buffer, _In_ UINT32 BufferLength) buffer = buffer + AES_256_BLOCK_SIZE; length = length - AES_256_BLOCK_SIZE; - status = BCryptEncrypt(session->key_handle, - buffer, - length, - NULL, - local_iv, - sizeof(local_iv), - buffer, - length, - &data_copied, - 0); + status = BCryptEncrypt( + session->key_handle, + buffer, + length, + NULL, + local_iv, + sizeof(local_iv), + buffer, + length, + &data_copied, + 0); if (!NT_SUCCESS(status)) DEBUG_ERROR("CryptEncryptBuffer -> BCryptEncrypt: %x", status); @@ -265,52 +271,55 @@ CryptCloseSessionCryptObjects() NTSTATUS CryptInitialiseSessionCryptObjects() { - NTSTATUS status = STATUS_UNSUCCESSFUL; - UINT32 data_copied = 0; - PACTIVE_SESSION session = GetActiveSession(); - PBCRYPT_KEY_DATA_BLOB_HEADER blob = NULL; - BCRYPT_ALG_HANDLE* handle = GetCryptHandle_AES(); + NTSTATUS status = STATUS_UNSUCCESSFUL; + UINT32 data_copied = 0; + PACTIVE_SESSION session = GetActiveSession(); + PBCRYPT_KEY_DATA_BLOB_HEADER blob = NULL; + BCRYPT_ALG_HANDLE* handle = GetCryptHandle_AES(); blob = CryptBuildBlobForKeyImport(session); if (!blob) return STATUS_INSUFFICIENT_RESOURCES; - status = BCryptGetProperty(*handle, - BCRYPT_OBJECT_LENGTH, - &session->key_object_length, - sizeof(UINT32), - &data_copied, - 0); + status = BCryptGetProperty( + *handle, + BCRYPT_OBJECT_LENGTH, + &session->key_object_length, + sizeof(UINT32), + &data_copied, + 0); if (!NT_SUCCESS(status)) { DEBUG_ERROR("BCryptGetProperty: %x", status); goto end; } - session->key_object = ExAllocatePool2(POOL_FLAG_NON_PAGED, - session->key_object_length, - POOL_TAG_CRYPT); + session->key_object = ExAllocatePool2( + POOL_FLAG_NON_PAGED, + session->key_object_length, + POOL_TAG_CRYPT); if (!session->key_object) { status = STATUS_INSUFFICIENT_RESOURCES; goto end; } - DEBUG_INFO("key object: %llx, key_object_length: %lx", - session->key_object, - session->key_object_length); + DEBUG_INFO( + "key object: %llx, key_object_length: %lx", + session->key_object, + session->key_object_length); - status = - BCryptImportKey(*handle, - NULL, - BCRYPT_KEY_DATA_BLOB, - &session->key_handle, - session->key_object, - session->key_object_length, - blob, - sizeof(BCRYPT_KEY_DATA_BLOB_HEADER) + AES_256_KEY_SIZE, - 0); + status = BCryptImportKey( + *handle, + NULL, + BCRYPT_KEY_DATA_BLOB, + &session->key_handle, + session->key_object, + session->key_object_length, + blob, + sizeof(BCRYPT_KEY_DATA_BLOB_HEADER) + AES_256_KEY_SIZE, + 0); if (!NT_SUCCESS(status)) { DEBUG_ERROR("BCryptImportKey: %x", status); @@ -328,13 +337,14 @@ end: NTSTATUS CryptInitialiseProvider() { - NTSTATUS status = STATUS_UNSUCCESSFUL; + NTSTATUS status = STATUS_UNSUCCESSFUL; BCRYPT_ALG_HANDLE* handle = GetCryptHandle_AES(); - status = BCryptOpenAlgorithmProvider(handle, - BCRYPT_AES_ALGORITHM, - NULL, - BCRYPT_PROV_DISPATCH); + status = BCryptOpenAlgorithmProvider( + handle, + BCRYPT_AES_ALGORITHM, + NULL, + BCRYPT_PROV_DISPATCH); if (!NT_SUCCESS(status)) DEBUG_ERROR("BCryptOpenAlgorithmProvider: %x", status); @@ -384,7 +394,7 @@ STATIC NTSTATUS TpmCheckPtpRegisterPresence(_In_ PVOID Register, _Out_ PUINT32 Result) { - UINT8 value = 0; + UINT8 value = 0; NTSTATUS status = STATUS_UNSUCCESSFUL; *Result = FALSE; @@ -406,7 +416,7 @@ FORCEINLINE STATIC TPM2_PTP_INTERFACE_TYPE TpmExtractInterfaceTypeFromCapabilityAndId( - _In_ PTP_CRB_INTERFACE_IDENTIFIER* Identifier, + _In_ PTP_CRB_INTERFACE_IDENTIFIER* Identifier, _In_ PTP_FIFO_INTERFACE_CAPABILITY* Capability) { if ((Identifier->Bits.InterfaceType == @@ -441,11 +451,11 @@ TpmExtractInterfaceTypeFromCapabilityAndId( */ STATIC NTSTATUS -TpmGetPtpInterfaceType(_In_ PVOID Register, - _Out_ TPM2_PTP_INTERFACE_TYPE* InterfaceType) +TpmGetPtpInterfaceType( + _In_ PVOID Register, _Out_ TPM2_PTP_INTERFACE_TYPE* InterfaceType) { - NTSTATUS status = STATUS_UNSUCCESSFUL; - PTP_CRB_INTERFACE_IDENTIFIER identifier = {0}; + NTSTATUS status = STATUS_UNSUCCESSFUL; + PTP_CRB_INTERFACE_IDENTIFIER identifier = {0}; PTP_FIFO_INTERFACE_CAPABILITY capability = {0}; *InterfaceType = 0; @@ -481,9 +491,9 @@ TpmGetPtpInterfaceType(_In_ PVOID Register, NTSTATUS TpmExtractEndorsementKey() { - NTSTATUS status = STATUS_UNSUCCESSFUL; - BOOLEAN presence = FALSE; - TPM2_PTP_INTERFACE_TYPE type = {0}; + NTSTATUS status = STATUS_UNSUCCESSFUL; + BOOLEAN presence = FALSE; + TPM2_PTP_INTERFACE_TYPE type = {0}; if (!TpmIsPlatformSupported()) return STATUS_NOT_SUPPORTED; @@ -512,23 +522,24 @@ TpmExtractEndorsementKey() } NTSTATUS -CryptHashBuffer_sha256(_In_ PVOID Buffer, - _In_ ULONG BufferSize, - _Out_ PVOID* HashResult, - _Out_ PULONG HashResultSize) +CryptHashBuffer_sha256( + _In_ PVOID Buffer, + _In_ ULONG BufferSize, + _Out_ PVOID* HashResult, + _Out_ PULONG HashResultSize) { PAGED_CODE(); - NTSTATUS status = STATUS_UNSUCCESSFUL; - BCRYPT_ALG_HANDLE* algo_handle = GetCryptHandle_Sha256(); - BCRYPT_HASH_HANDLE hash_handle = NULL; - ULONG bytes_copied = 0; - ULONG resulting_hash_size = 0; - ULONG hash_object_size = 0; - PCHAR hash_object = NULL; - PCHAR resulting_hash = NULL; + NTSTATUS status = STATUS_UNSUCCESSFUL; + BCRYPT_ALG_HANDLE* algo_handle = GetCryptHandle_Sha256(); + BCRYPT_HASH_HANDLE hash_handle = NULL; + ULONG bytes_copied = 0; + ULONG resulting_hash_size = 0; + ULONG hash_object_size = 0; + PCHAR hash_object = NULL; + PCHAR resulting_hash = NULL; - *HashResult = NULL; + *HashResult = NULL; *HashResultSize = 0; /* @@ -536,21 +547,23 @@ CryptHashBuffer_sha256(_In_ PVOID Buffer, * the buffer that will store the resulting hash, instead this will be * used to store the hash object used to create the hash. */ - status = BCryptGetProperty(*algo_handle, - BCRYPT_OBJECT_LENGTH, - (PCHAR)&hash_object_size, - sizeof(ULONG), - &bytes_copied, - NULL); + status = BCryptGetProperty( + *algo_handle, + BCRYPT_OBJECT_LENGTH, + (PCHAR)&hash_object_size, + sizeof(ULONG), + &bytes_copied, + NULL); if (!NT_SUCCESS(status)) { DEBUG_ERROR("BCryptGetProperty failed with status %x", status); goto end; } - hash_object = ImpExAllocatePool2(POOL_FLAG_NON_PAGED, - hash_object_size, - POOL_TAG_INTEGRITY); + hash_object = ImpExAllocatePool2( + POOL_FLAG_NON_PAGED, + hash_object_size, + POOL_TAG_INTEGRITY); if (!hash_object) { status = STATUS_MEMORY_NOT_ALLOCATED; @@ -561,21 +574,23 @@ CryptHashBuffer_sha256(_In_ PVOID Buffer, * This call gets the size of the resulting hash, which we will use to * allocate the resulting hash buffer. */ - status = BCryptGetProperty(*algo_handle, - BCRYPT_HASH_LENGTH, - (PCHAR)&resulting_hash_size, - sizeof(ULONG), - &bytes_copied, - NULL); + status = BCryptGetProperty( + *algo_handle, + BCRYPT_HASH_LENGTH, + (PCHAR)&resulting_hash_size, + sizeof(ULONG), + &bytes_copied, + NULL); if (!NT_SUCCESS(status)) { DEBUG_ERROR("BCryptGetProperty failed with status %x", status); goto end; } - resulting_hash = ImpExAllocatePool2(POOL_FLAG_NON_PAGED, - resulting_hash_size, - POOL_TAG_INTEGRITY); + resulting_hash = ImpExAllocatePool2( + POOL_FLAG_NON_PAGED, + resulting_hash_size, + POOL_TAG_INTEGRITY); if (!resulting_hash) { status = STATUS_MEMORY_NOT_ALLOCATED; @@ -586,13 +601,14 @@ CryptHashBuffer_sha256(_In_ PVOID Buffer, * Here we create our hash object and store it in the hash_object * buffer. */ - status = BCryptCreateHash(*algo_handle, - &hash_handle, - hash_object, - hash_object_size, - NULL, - NULL, - NULL); + status = BCryptCreateHash( + *algo_handle, + &hash_handle, + hash_object, + hash_object_size, + NULL, + NULL, + NULL); if (!NT_SUCCESS(status)) { DEBUG_ERROR("BCryptCreateHash failed with status %x", status); @@ -615,17 +631,18 @@ CryptHashBuffer_sha256(_In_ PVOID Buffer, * As said in the previous comment, this is where we retrieve the final * hash and store it in our output buffer. */ - status = BCryptFinishHash(hash_handle, - resulting_hash, - resulting_hash_size, - NULL); + status = BCryptFinishHash( + hash_handle, + resulting_hash, + resulting_hash_size, + NULL); if (!NT_SUCCESS(status)) { DEBUG_ERROR("BCryptFinishHash failed with status %x", status); goto end; } - *HashResult = resulting_hash; + *HashResult = resulting_hash; *HashResultSize = resulting_hash_size; end: diff --git a/driver/driver.c b/driver/driver.c index 3f80273..df03d4b 100644 --- a/driver/driver.c +++ b/driver/driver.c @@ -1,18 +1,18 @@ #include "driver.h" -#include "common.h" -#include "io.h" -#include "callbacks.h" -#include "hv.h" -#include "pool.h" -#include "thread.h" -#include "modules.h" -#include "integrity.h" -#include "imports.h" #include "apc.h" +#include "callbacks.h" +#include "common.h" #include "crypt.h" -#include "session.h" +#include "hv.h" #include "hw.h" +#include "imports.h" +#include "integrity.h" +#include "io.h" +#include "modules.h" +#include "pool.h" +#include "session.h" +#include "thread.h" #include "lib/stdlib.h" @@ -24,17 +24,18 @@ DriverUnload(_In_ PDRIVER_OBJECT DriverObject); _Function_class_(DRIVER_INITIALIZE) _IRQL_requires_same_ NTSTATUS -DriverEntry(_In_ PDRIVER_OBJECT DriverObject, - _In_ PUNICODE_STRING RegistryPath); +DriverEntry( + _In_ PDRIVER_OBJECT DriverObject, _In_ PUNICODE_STRING RegistryPath); STATIC NTSTATUS -RegistryPathQueryCallbackRoutine(IN PWSTR ValueName, - IN ULONG ValueType, - IN PVOID ValueData, - IN ULONG ValueLength, - IN PVOID Context, - IN PVOID EntryContext); +RegistryPathQueryCallbackRoutine( + IN PWSTR ValueName, + IN ULONG ValueType, + IN PVOID ValueData, + IN ULONG ValueLength, + IN PVOID Context, + IN PVOID EntryContext); STATIC VOID @@ -58,8 +59,8 @@ DrvLoadEnableNotifyRoutines(); STATIC NTSTATUS -DrvLoadInitialiseDriverConfig(_In_ PDRIVER_OBJECT DriverObject, - _In_ PUNICODE_STRING RegistryPath); +DrvLoadInitialiseDriverConfig( + _In_ PDRIVER_OBJECT DriverObject, _In_ PUNICODE_STRING RegistryPath); #ifdef ALLOC_PRAGMA # pragma alloc_text(INIT, DriverEntry) @@ -79,33 +80,33 @@ DrvLoadInitialiseDriverConfig(_In_ PDRIVER_OBJECT DriverObject, #endif typedef struct _DRIVER_CONFIG { - volatile UINT32 nmi_status; - UNICODE_STRING unicode_driver_name; - ANSI_STRING ansi_driver_name; - PUNICODE_STRING device_name; - PUNICODE_STRING device_symbolic_link; - UNICODE_STRING driver_path; - UNICODE_STRING registry_path; - SYSTEM_INFORMATION system_information; - PVOID apc_contexts[MAXIMUM_APC_CONTEXTS]; - PDRIVER_OBJECT driver_object; - PDEVICE_OBJECT device_object; - volatile BOOLEAN unload_in_progress; - KGUARDED_MUTEX lock; + volatile UINT32 nmi_status; + UNICODE_STRING unicode_driver_name; + ANSI_STRING ansi_driver_name; + PUNICODE_STRING device_name; + PUNICODE_STRING device_symbolic_link; + UNICODE_STRING driver_path; + UNICODE_STRING registry_path; + SYSTEM_INFORMATION system_information; + PVOID apc_contexts[MAXIMUM_APC_CONTEXTS]; + PDRIVER_OBJECT driver_object; + PDEVICE_OBJECT device_object; + volatile BOOLEAN unload_in_progress; + KGUARDED_MUTEX lock; SYS_MODULE_VAL_CONTEXT sys_val_context; - IRP_QUEUE_HEAD irp_queue; - TIMER_OBJECT integrity_check_timer; - ACTIVE_SESSION session_information; - RB_TREE thread_tree; - DRIVER_LIST_HEAD driver_list; - RTL_HASHMAP process_hashmap; - SHARED_MAPPING mapping; - BOOLEAN has_driver_loaded; - BCRYPT_ALG_HANDLE aes_hash; - BCRYPT_ALG_HANDLE sha256_hash; + IRP_QUEUE_HEAD irp_queue; + TIMER_OBJECT integrity_check_timer; + ACTIVE_SESSION session_information; + RB_TREE thread_tree; + DRIVER_LIST_HEAD driver_list; + RTL_HASHMAP process_hashmap; + SHARED_MAPPING mapping; + BOOLEAN has_driver_loaded; + BCRYPT_ALG_HANDLE aes_hash; + BCRYPT_ALG_HANDLE sha256_hash; } DRIVER_CONFIG, *PDRIVER_CONFIG; -UNICODE_STRING g_DeviceName = RTL_CONSTANT_STRING(L"\\Device\\DonnaAC"); +UNICODE_STRING g_DeviceName = RTL_CONSTANT_STRING(L"\\Device\\DonnaAC"); UNICODE_STRING g_DeviceSymbolicLink = RTL_CONSTANT_STRING(L"\\??\\DonnaAC"); /* xor key generated on driver entry used to encrypt the imports array. Kept in @@ -218,9 +219,10 @@ BOOLEAN IsNmiInProgress() { PAGED_CODE(); - return InterlockedCompareExchange(&GetDecryptedDriverConfig()->nmi_status, - TRUE, - FALSE) != 0; + return InterlockedCompareExchange( + &GetDecryptedDriverConfig()->nmi_status, + TRUE, + FALSE) != 0; } PSHARED_MAPPING @@ -255,8 +257,9 @@ BOOLEAN IsDriverUnloading() { PAGED_CODE(); - return InterlockedExchange(&GetDecryptedDriverConfig()->unload_in_progress, - GetDecryptedDriverConfig()->unload_in_progress); + return InterlockedExchange( + &GetDecryptedDriverConfig()->unload_in_progress, + GetDecryptedDriverConfig()->unload_in_progress); } PACTIVE_SESSION @@ -492,16 +495,18 @@ DrvLoadEnableNotifyRoutines() status = PsSetLoadImageNotifyRoutine(ImageLoadNotifyRoutineCallback); if (!NT_SUCCESS(status)) { - DEBUG_ERROR("PsSetLoadImageNotifyRoutine failed with status %x", - status); + DEBUG_ERROR( + "PsSetLoadImageNotifyRoutine failed with status %x", + status); return status; } status = ImpPsSetCreateThreadNotifyRoutine(ThreadCreateNotifyRoutine); if (!NT_SUCCESS(status)) { - DEBUG_ERROR("PsSetCreateThreadNotifyRoutine failed with status %x", - status); + DEBUG_ERROR( + "PsSetCreateThreadNotifyRoutine failed with status %x", + status); PsRemoveLoadImageNotifyRoutine(ImageLoadNotifyRoutineCallback); return status; } @@ -510,8 +515,9 @@ DrvLoadEnableNotifyRoutines() ImpPsSetCreateProcessNotifyRoutine(ProcessCreateNotifyRoutine, FALSE); if (!NT_SUCCESS(status)) { - DEBUG_ERROR("PsSetCreateProcessNotifyRoutine failed with status %x", - status); + DEBUG_ERROR( + "PsSetCreateProcessNotifyRoutine failed with status %x", + status); ImpPsRemoveCreateThreadNotifyRoutine(ThreadCreateNotifyRoutine); PsRemoveLoadImageNotifyRoutine(ImageLoadNotifyRoutineCallback); return status; @@ -571,20 +577,21 @@ DrvLoadSetupDriverLists() STATIC NTSTATUS -RegistryPathQueryCallbackRoutine(IN PWSTR ValueName, - IN ULONG ValueType, - IN PVOID ValueData, - IN ULONG ValueLength, - IN PVOID Context, - IN PVOID EntryContext) +RegistryPathQueryCallbackRoutine( + IN PWSTR ValueName, + IN ULONG ValueType, + IN PVOID ValueData, + IN ULONG ValueLength, + IN PVOID Context, + IN PVOID EntryContext) { PAGED_CODE(); - UNICODE_STRING value_name = {0}; - UNICODE_STRING image_path = RTL_CONSTANT_STRING(L"ImagePath"); + UNICODE_STRING value_name = {0}; + UNICODE_STRING image_path = RTL_CONSTANT_STRING(L"ImagePath"); UNICODE_STRING display_name = RTL_CONSTANT_STRING(L"DisplayName"); - UNICODE_STRING value = {0}; - PVOID temp_buffer = NULL; + UNICODE_STRING value = {0}; + PVOID temp_buffer = NULL; ImpRtlInitUnicodeString(&value_name, ValueName); @@ -599,26 +606,28 @@ RegistryPathQueryCallbackRoutine(IN PWSTR ValueName, IntCopyMemory(temp_buffer, ValueData, ValueLength); - cfg->driver_path.Buffer = (PWCH)temp_buffer; - cfg->driver_path.Length = ValueLength; + cfg->driver_path.Buffer = (PWCH)temp_buffer; + cfg->driver_path.Length = ValueLength; cfg->driver_path.MaximumLength = ValueLength; } if (ImpRtlCompareUnicodeString(&value_name, &display_name, FALSE) == FALSE) { - temp_buffer = ImpExAllocatePool2(POOL_FLAG_PAGED, - ValueLength + 20, - POOL_TAG_STRINGS); + temp_buffer = ImpExAllocatePool2( + POOL_FLAG_PAGED, + ValueLength + 20, + POOL_TAG_STRINGS); if (!temp_buffer) return STATUS_MEMORY_NOT_ALLOCATED; IntCopyMemory(temp_buffer, ValueData, ValueLength); - IntWideStringCopy((PWCH)((UINT64)temp_buffer + ValueLength - 2), - L".sys"); + IntWideStringCopy( + (PWCH)((UINT64)temp_buffer + ValueLength - 2), + L".sys"); - cfg->unicode_driver_name.Buffer = (PWCH)temp_buffer; - cfg->unicode_driver_name.Length = ValueLength + 20; + cfg->unicode_driver_name.Buffer = (PWCH)temp_buffer; + cfg->unicode_driver_name.Length = ValueLength + 20; cfg->unicode_driver_name.MaximumLength = ValueLength + 20; } @@ -644,15 +653,16 @@ STATIC NTSTATUS GetSystemProcessorType() { - UINT32 cpuid[4] = {0}; - PDRIVER_CONFIG cfg = GetDecryptedDriverConfig(); + UINT32 cpuid[4] = {0}; + PDRIVER_CONFIG cfg = GetDecryptedDriverConfig(); __cpuid(cpuid, 0); - DEBUG_VERBOSE("Cpuid: EBX: %lx, ECX: %lx, EDX: %lx", - cpuid[1], - cpuid[2], - cpuid[3]); + DEBUG_VERBOSE( + "Cpuid: EBX: %lx, ECX: %lx, EDX: %lx", + cpuid[1], + cpuid[2], + cpuid[3]); if (cpuid[EBX_REGISTER] == CPUID_AUTHENTIC_AMD_EBX && cpuid[ECX_REGISTER] == CPUID_AUTHENTIC_AMD_ECX && @@ -660,9 +670,10 @@ GetSystemProcessorType() cfg->system_information.processor = AuthenticAmd; return STATUS_SUCCESS; } - else if (cpuid[EBX_REGISTER] == CPUID_GENUINE_INTEL_EBX && - cpuid[ECX_REGISTER] == CPUID_GENUINE_INTEL_ECX && - cpuid[EDX_REGISTER] == CPUID_GENUINE_INTEL_EDX) { + else if ( + cpuid[EBX_REGISTER] == CPUID_GENUINE_INTEL_EBX && + cpuid[ECX_REGISTER] == CPUID_GENUINE_INTEL_ECX && + cpuid[EDX_REGISTER] == CPUID_GENUINE_INTEL_EDX) { cfg->system_information.processor = GenuineIntel; return STATUS_SUCCESS; } @@ -681,13 +692,14 @@ STATIC NTSTATUS ParseSmbiosForGivenSystemEnvironment() { - NTSTATUS status = STATUS_UNSUCCESSFUL; - PDRIVER_CONFIG cfg = GetDecryptedDriverConfig(); + NTSTATUS status = STATUS_UNSUCCESSFUL; + PDRIVER_CONFIG cfg = GetDecryptedDriverConfig(); - status = ParseSMBIOSTable(&cfg->system_information.vendor, - VENDOR_STRING_MAX_LENGTH, - SmbiosInformation, - SMBIOS_VENDOR_STRING_SUB_INDEX); + status = ParseSMBIOSTable( + &cfg->system_information.vendor, + VENDOR_STRING_MAX_LENGTH, + SmbiosInformation, + SMBIOS_VENDOR_STRING_SUB_INDEX); if (!NT_SUCCESS(status)) { DEBUG_ERROR("ParseSMBIOSTable failed with status %x", status); @@ -703,17 +715,19 @@ ParseSmbiosForGivenSystemEnvironment() switch (cfg->system_information.environment) { case NativeWindows: { - status = ParseSMBIOSTable(&cfg->system_information.motherboard_serial, - MOTHERBOARD_SERIAL_CODE_LENGTH, - VendorSpecificInformation, - SMBIOS_NATIVE_SERIAL_NUMBER_SUB_INDEX); + status = ParseSMBIOSTable( + &cfg->system_information.motherboard_serial, + MOTHERBOARD_SERIAL_CODE_LENGTH, + VendorSpecificInformation, + SMBIOS_NATIVE_SERIAL_NUMBER_SUB_INDEX); break; } case Vmware: { - status = ParseSMBIOSTable(&cfg->system_information.motherboard_serial, - MOTHERBOARD_SERIAL_CODE_LENGTH, - SystemInformation, - SMBIOS_VMWARE_SERIAL_NUMBER_SUB_INDEX); + status = ParseSMBIOSTable( + &cfg->system_information.motherboard_serial, + MOTHERBOARD_SERIAL_CODE_LENGTH, + SystemInformation, + SMBIOS_VMWARE_SERIAL_NUMBER_SUB_INDEX); break; } case VirtualBox: @@ -734,8 +748,8 @@ STATIC NTSTATUS DrvLoadGatherSystemEnvironmentSettings() { - NTSTATUS status = STATUS_UNSUCCESSFUL; - PDRIVER_CONFIG cfg = GetDecryptedDriverConfig(); + NTSTATUS status = STATUS_UNSUCCESSFUL; + PDRIVER_CONFIG cfg = GetDecryptedDriverConfig(); if (APERFMsrTimingCheck()) cfg->system_information.virtualised_environment = TRUE; @@ -768,8 +782,9 @@ DrvLoadGatherSystemEnvironmentSettings() sizeof(cfg->system_information.drive_0_serial)); if (!NT_SUCCESS(status)) { - DEBUG_ERROR("GetHardDiskDriverSerialNumber failed with status %x", - status); + DEBUG_ERROR( + "GetHardDiskDriverSerialNumber failed with status %x", + status); return status; } @@ -780,8 +795,9 @@ DrvLoadGatherSystemEnvironmentSettings() cfg->system_information.os_information.dwBuildNumber); DEBUG_VERBOSE("Environment type: %lx", cfg->system_information.environment); DEBUG_VERBOSE("Processor type: %lx", cfg->system_information.processor); - DEBUG_VERBOSE("Motherboard serial: %s", - cfg->system_information.motherboard_serial); + DEBUG_VERBOSE( + "Motherboard serial: %s", + cfg->system_information.motherboard_serial); DEBUG_VERBOSE("Drive 0 serial: %s", cfg->system_information.drive_0_serial); return status; @@ -791,31 +807,32 @@ STATIC NTSTATUS DrvLoadRetrieveDriverNameFromRegistry(_In_ PUNICODE_STRING RegistryPath) { - NTSTATUS status = STATUS_UNSUCCESSFUL; - PDRIVER_CONFIG cfg = GetDecryptedDriverConfig(); + NTSTATUS status = STATUS_UNSUCCESSFUL; + PDRIVER_CONFIG cfg = GetDecryptedDriverConfig(); RTL_QUERY_REGISTRY_TABLE query[3] = {0}; - query[0].Flags = RTL_QUERY_REGISTRY_NOEXPAND; - query[0].Name = L"ImagePath"; - query[0].DefaultType = REG_MULTI_SZ; + query[0].Flags = RTL_QUERY_REGISTRY_NOEXPAND; + query[0].Name = L"ImagePath"; + query[0].DefaultType = REG_MULTI_SZ; query[0].DefaultLength = 0; - query[0].DefaultData = NULL; - query[0].EntryContext = NULL; - query[0].QueryRoutine = RegistryPathQueryCallbackRoutine; + query[0].DefaultData = NULL; + query[0].EntryContext = NULL; + query[0].QueryRoutine = RegistryPathQueryCallbackRoutine; - query[1].Flags = RTL_QUERY_REGISTRY_NOEXPAND; - query[1].Name = L"DisplayName"; - query[1].DefaultType = REG_SZ; + query[1].Flags = RTL_QUERY_REGISTRY_NOEXPAND; + query[1].Name = L"DisplayName"; + query[1].DefaultType = REG_SZ; query[1].DefaultLength = 0; - query[1].DefaultData = NULL; - query[1].EntryContext = NULL; - query[1].QueryRoutine = RegistryPathQueryCallbackRoutine; + query[1].DefaultData = NULL; + query[1].EntryContext = NULL; + query[1].QueryRoutine = RegistryPathQueryCallbackRoutine; - status = RtlxQueryRegistryValues(RTL_REGISTRY_ABSOLUTE, - RegistryPath->Buffer, - &query, - NULL, - NULL); + status = RtlxQueryRegistryValues( + RTL_REGISTRY_ABSOLUTE, + RegistryPath->Buffer, + &query, + NULL, + NULL); if (!NT_SUCCESS(status)) { DEBUG_ERROR("RtlxQueryRegistryValues failed with status %x", status); @@ -828,13 +845,15 @@ DrvLoadRetrieveDriverNameFromRegistry(_In_ PUNICODE_STRING RegistryPath) * name since we need the .sys extension when querying the system * modules for our driver. */ - status = ImpRtlUnicodeStringToAnsiString(&cfg->ansi_driver_name, - &cfg->unicode_driver_name, - TRUE); + status = ImpRtlUnicodeStringToAnsiString( + &cfg->ansi_driver_name, + &cfg->unicode_driver_name, + TRUE); if (!NT_SUCCESS(status)) { - DEBUG_ERROR("RtlUnicodeStringToAnsiString failed with status %x", - status); + DEBUG_ERROR( + "RtlUnicodeStringToAnsiString failed with status %x", + status); } return status; @@ -842,23 +861,23 @@ DrvLoadRetrieveDriverNameFromRegistry(_In_ PUNICODE_STRING RegistryPath) STATIC NTSTATUS -DrvLoadInitialiseDriverConfig(_In_ PDRIVER_OBJECT DriverObject, - _In_ PUNICODE_STRING RegistryPath) +DrvLoadInitialiseDriverConfig( + _In_ PDRIVER_OBJECT DriverObject, _In_ PUNICODE_STRING RegistryPath) { PAGED_CODE(); DEBUG_VERBOSE("Initialising driver configuration"); - NTSTATUS status = STATUS_UNSUCCESSFUL; - PDRIVER_CONFIG cfg = GetDecryptedDriverConfig(); + NTSTATUS status = STATUS_UNSUCCESSFUL; + PDRIVER_CONFIG cfg = GetDecryptedDriverConfig(); ImpKeInitializeGuardedMutex(&cfg->lock); IrpQueueInitialise(); SessionInitialiseCallbackConfiguration(); - cfg->unload_in_progress = FALSE; + cfg->unload_in_progress = FALSE; cfg->system_information.virtualised_environment = FALSE; - cfg->sys_val_context.active = FALSE; + cfg->sys_val_context.active = FALSE; status = DrvLoadRetrieveDriverNameFromRegistry(RegistryPath); @@ -873,8 +892,9 @@ DrvLoadInitialiseDriverConfig(_In_ PDRIVER_OBJECT DriverObject, status = DrvLoadGatherSystemEnvironmentSettings(); if (!NT_SUCCESS(status)) { - DEBUG_ERROR("GatherSystemEnvironmentSettings failed with status %x", - status); + DEBUG_ERROR( + "GatherSystemEnvironmentSettings failed with status %x", + status); return status; } @@ -900,13 +920,14 @@ STATIC NTSTATUS InitialiseHashingAlgorithmProvider() { - NTSTATUS status = STATUS_UNSUCCESSFUL; + NTSTATUS status = STATUS_UNSUCCESSFUL; BCRYPT_ALG_HANDLE* handle = GetCryptHandle_Sha256(); - status = BCryptOpenAlgorithmProvider(handle, - BCRYPT_SHA256_ALGORITHM, - NULL, - BCRYPT_PROV_DISPATCH); + status = BCryptOpenAlgorithmProvider( + handle, + BCRYPT_SHA256_ALGORITHM, + NULL, + BCRYPT_PROV_DISPATCH); if (!NT_SUCCESS(status)) DEBUG_ERROR("BCryptOpenAlgorithmProvider: %x", status); @@ -917,13 +938,13 @@ InitialiseHashingAlgorithmProvider() NTSTATUS DriverEntry(_In_ PDRIVER_OBJECT DriverObject, _In_ PUNICODE_STRING RegistryPath) { - BOOLEAN flag = FALSE; + BOOLEAN flag = FALSE; NTSTATUS status = STATUS_UNSUCCESSFUL; - DriverObject->MajorFunction[IRP_MJ_CREATE] = DeviceCreate; - DriverObject->MajorFunction[IRP_MJ_CLOSE] = DeviceClose; + DriverObject->MajorFunction[IRP_MJ_CREATE] = DeviceCreate; + DriverObject->MajorFunction[IRP_MJ_CLOSE] = DeviceClose; DriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL] = DeviceControl; - DriverObject->DriverUnload = DriverUnload; + DriverObject->DriverUnload = DriverUnload; g_DeviceExtensionKey = CryptXorKeyGenerate_uint64(); @@ -934,23 +955,24 @@ DriverEntry(_In_ PDRIVER_OBJECT DriverObject, _In_ PUNICODE_STRING RegistryPath) DEBUG_VERBOSE("Beginning driver entry routine..."); - status = ImpIoCreateDevice(DriverObject, - sizeof(DRIVER_CONFIG), - &g_DeviceName, - FILE_DEVICE_UNKNOWN, - FILE_DEVICE_SECURE_OPEN, - FALSE, - &DriverObject->DeviceObject); + status = ImpIoCreateDevice( + DriverObject, + sizeof(DRIVER_CONFIG), + &g_DeviceName, + FILE_DEVICE_UNKNOWN, + FILE_DEVICE_SECURE_OPEN, + FALSE, + &DriverObject->DeviceObject); if (!NT_SUCCESS(status)) { DEBUG_ERROR("IoCreateDevice failed with status %x", status); return status; } - g_DriverConfig = DriverObject->DeviceObject->DeviceExtension; + g_DriverConfig = DriverObject->DeviceObject->DeviceExtension; g_DriverConfig->device_object = DriverObject->DeviceObject; g_DriverConfig->driver_object = DriverObject; - g_DriverConfig->device_name = &g_DeviceName; + g_DriverConfig->device_name = &g_DeviceName; g_DriverConfig->device_symbolic_link = &g_DeviceSymbolicLink; EncryptDeviceExtensionPointers(DriverObject->DeviceObject); @@ -958,8 +980,9 @@ DriverEntry(_In_ PDRIVER_OBJECT DriverObject, _In_ PUNICODE_STRING RegistryPath) status = DrvLoadInitialiseDriverConfig(DriverObject, RegistryPath); if (!NT_SUCCESS(status)) { - DEBUG_ERROR("InitialiseDriverConfigOnDriverEntry failed with status %x", - status); + DEBUG_ERROR( + "InitialiseDriverConfigOnDriverEntry failed with status %x", + status); DrvUnloadFreeConfigStrings(); ImpIoDeleteDevice(GetDecryptedDriverConfig()->device_object); return status; @@ -975,9 +998,9 @@ DriverEntry(_In_ PDRIVER_OBJECT DriverObject, _In_ PUNICODE_STRING RegistryPath) return status; } - status = - IoCreateSymbolicLink(GetDecryptedDriverConfig()->device_symbolic_link, - GetDecryptedDriverConfig()->device_name); + status = IoCreateSymbolicLink( + GetDecryptedDriverConfig()->device_symbolic_link, + GetDecryptedDriverConfig()->device_name); if (!NT_SUCCESS(status)) { DEBUG_ERROR("IoCreateSymbolicLink failed with status %x", status); @@ -1001,8 +1024,9 @@ DriverEntry(_In_ PDRIVER_OBJECT DriverObject, _In_ PUNICODE_STRING RegistryPath) status = InitialiseHashingAlgorithmProvider(); if (!NT_SUCCESS(status)) { - DEBUG_ERROR("InitialiseHashingAlgorithmProvider failed with status %x", - status); + DEBUG_ERROR( + "InitialiseHashingAlgorithmProvider failed with status %x", + status); DrvUnloadFreeConfigStrings(); DrvUnloadFreeTimerObject(); DrvUnloadDeleteSymbolicLink(); diff --git a/driver/hv.c b/driver/hv.c index 3b2a3b7..5f34c0e 100644 --- a/driver/hv.c +++ b/driver/hv.c @@ -1,9 +1,9 @@ #include "hv.h" -#include -#include "imports.h" #include "common.h" +#include "imports.h" #include "io.h" +#include #include "lib/stdlib.h" @@ -29,8 +29,8 @@ APERFMsrTimingCheck() { KAFFINITY new_affinity = {0}; KAFFINITY old_affinity = {0}; - UINT64 old_irql = 0; - INT cpuid_result[4]; + UINT64 old_irql = 0; + INT cpuid_result[4]; /* * First thing we do is we lock the current thread to the logical @@ -98,14 +98,15 @@ PerformVirtualizationDetection(_Inout_ PIRP Irp) } HYPERVISOR_DETECTION_REPORT report = {0}; - report.aperf_msr_timing_check = APERFMsrTimingCheck(); - report.invd_emulation_check = TestINVDEmulation(); + report.aperf_msr_timing_check = APERFMsrTimingCheck(); + report.invd_emulation_check = TestINVDEmulation(); Irp->IoStatus.Information = sizeof(HYPERVISOR_DETECTION_REPORT); - IntCopyMemory(Irp->AssociatedIrp.SystemBuffer, - &report, - sizeof(HYPERVISOR_DETECTION_REPORT)); + IntCopyMemory( + Irp->AssociatedIrp.SystemBuffer, + &report, + sizeof(HYPERVISOR_DETECTION_REPORT)); return STATUS_SUCCESS; } \ No newline at end of file diff --git a/driver/hw.c b/driver/hw.c index 8ae3a62..3b143d2 100644 --- a/driver/hw.c +++ b/driver/hw.c @@ -1,8 +1,8 @@ #include "hw.h" -#include "modules.h" #include "crypt.h" #include "imports.h" +#include "modules.h" #include "lib/stdlib.h" @@ -15,8 +15,8 @@ USHORT FLAGGED_DEVICE_IDS[FLAGGED_DEVICE_ID_COUNT] = { 0x0666, // default PCIe Squirrel DeviceID (used by PCI Leech) 0xffff}; -typedef NTSTATUS (*PCI_DEVICE_CALLBACK)(_In_ PDEVICE_OBJECT DeviceObject, - _In_opt_ PVOID Context); +typedef NTSTATUS (*PCI_DEVICE_CALLBACK)( + _In_ PDEVICE_OBJECT DeviceObject, _In_opt_ PVOID Context); /* * Every PCI device has a set of registers commonly referred to as the PCI @@ -66,15 +66,16 @@ typedef NTSTATUS (*PCI_DEVICE_CALLBACK)(_In_ PDEVICE_OBJECT DeviceObject, */ STATIC NTSTATUS -QueryPciDeviceConfigurationSpace(_In_ PDEVICE_OBJECT DeviceObject, - _In_ UINT32 Offset, - _Out_opt_ PVOID Buffer, - _In_ UINT32 BufferLength) +QueryPciDeviceConfigurationSpace( + _In_ PDEVICE_OBJECT DeviceObject, + _In_ UINT32 Offset, + _Out_opt_ PVOID Buffer, + _In_ UINT32 BufferLength) { - NTSTATUS status = STATUS_UNSUCCESSFUL; - KEVENT event = {0}; - IO_STATUS_BLOCK io = {0}; - PIRP irp = NULL; + NTSTATUS status = STATUS_UNSUCCESSFUL; + KEVENT event = {0}; + IO_STATUS_BLOCK io = {0}; + PIRP irp = NULL; PIO_STACK_LOCATION packet = NULL; if (BufferLength == 0) @@ -87,19 +88,25 @@ QueryPciDeviceConfigurationSpace(_In_ PDEVICE_OBJECT DeviceObject, * request is completed */ irp = IoBuildSynchronousFsdRequest( - IRP_MJ_PNP, DeviceObject, NULL, 0, NULL, &event, &io); + IRP_MJ_PNP, + DeviceObject, + NULL, + 0, + NULL, + &event, + &io); if (!irp) { DEBUG_ERROR("IoBuildSynchronousFsdRequest failed with no status."); return STATUS_INSUFFICIENT_RESOURCES; } - packet = IoGetNextIrpStackLocation(irp); + packet = IoGetNextIrpStackLocation(irp); packet->MinorFunction = IRP_MN_READ_CONFIG; packet->Parameters.ReadWriteConfig.WhichSpace = PCI_WHICHSPACE_CONFIG; - packet->Parameters.ReadWriteConfig.Offset = Offset; - packet->Parameters.ReadWriteConfig.Buffer = Buffer; - packet->Parameters.ReadWriteConfig.Length = BufferLength; + packet->Parameters.ReadWriteConfig.Offset = Offset; + packet->Parameters.ReadWriteConfig.Buffer = Buffer; + packet->Parameters.ReadWriteConfig.Length = BufferLength; status = IoCallDriver(DeviceObject, irp); @@ -109,8 +116,9 @@ QueryPciDeviceConfigurationSpace(_In_ PDEVICE_OBJECT DeviceObject, } if (!NT_SUCCESS(status)) - DEBUG_ERROR("Failed to read configuration space with status %x", - status); + DEBUG_ERROR( + "Failed to read configuration space with status %x", + status); return status; } @@ -120,23 +128,25 @@ QueryPciDeviceConfigurationSpace(_In_ PDEVICE_OBJECT DeviceObject, */ STATIC NTSTATUS -EnumerateDriverObjectDeviceObjects(_In_ PDRIVER_OBJECT DriverObject, - _Out_ PDEVICE_OBJECT** DeviceObjectArray, - _Out_ PUINT32 ArrayEntries) +EnumerateDriverObjectDeviceObjects( + _In_ PDRIVER_OBJECT DriverObject, + _Out_ PDEVICE_OBJECT** DeviceObjectArray, + _Out_ PUINT32 ArrayEntries) { - NTSTATUS status = STATUS_UNSUCCESSFUL; - UINT32 object_count = 0; - PDEVICE_OBJECT* buffer = NULL; - UINT32 buffer_size = 0; + NTSTATUS status = STATUS_UNSUCCESSFUL; + UINT32 object_count = 0; + PDEVICE_OBJECT* buffer = NULL; + UINT32 buffer_size = 0; *DeviceObjectArray = NULL; - *ArrayEntries = 0; + *ArrayEntries = 0; status = IoEnumerateDeviceObjectList(DriverObject, NULL, 0, &object_count); if (status != STATUS_BUFFER_TOO_SMALL) { - DEBUG_ERROR("IoEnumerateDeviceObjectList failed with status %x", - status); + DEBUG_ERROR( + "IoEnumerateDeviceObjectList failed with status %x", + status); return status; } @@ -147,20 +157,25 @@ EnumerateDriverObjectDeviceObjects(_In_ PDRIVER_OBJECT DriverObject, return STATUS_INSUFFICIENT_RESOURCES; status = IoEnumerateDeviceObjectList( - DriverObject, buffer, buffer_size, &object_count); + DriverObject, + buffer, + buffer_size, + &object_count); if (!NT_SUCCESS(status)) { - DEBUG_ERROR("IoEnumerateDeviceObjectList failed with status %x", - status); + DEBUG_ERROR( + "IoEnumerateDeviceObjectList failed with status %x", + status); ExFreePoolWithTag(buffer, POOL_TAG_HW); return status; } - DEBUG_VERBOSE("EnumerateDriverObjectDeviceObjects: Object Count: %lx", - object_count); + DEBUG_VERBOSE( + "EnumerateDriverObjectDeviceObjects: Object Count: %lx", + object_count); *DeviceObjectArray = buffer; - *ArrayEntries = object_count; + *ArrayEntries = object_count; return status; } @@ -195,30 +210,34 @@ IsDeviceObjectValidPdo(_In_ PDEVICE_OBJECT DeviceObject) * given the PCI FDO which is called pci.sys. */ NTSTATUS -EnumeratePciDeviceObjects(_In_ PCI_DEVICE_CALLBACK CallbackRoutine, - _In_opt_ PVOID Context) +EnumeratePciDeviceObjects( + _In_ PCI_DEVICE_CALLBACK CallbackRoutine, _In_opt_ PVOID Context) { - NTSTATUS status = STATUS_UNSUCCESSFUL; - UNICODE_STRING pci = RTL_CONSTANT_STRING(L"\\Driver\\pci"); - PDRIVER_OBJECT pci_driver_object = NULL; + NTSTATUS status = STATUS_UNSUCCESSFUL; + UNICODE_STRING pci = RTL_CONSTANT_STRING(L"\\Driver\\pci"); + PDRIVER_OBJECT pci_driver_object = NULL; PDEVICE_OBJECT* pci_device_objects = NULL; - PDEVICE_OBJECT current_device = NULL; - UINT32 pci_device_objects_count = 0; + PDEVICE_OBJECT current_device = NULL; + UINT32 pci_device_objects_count = 0; status = GetDriverObjectByDriverName(&pci, &pci_driver_object); if (!NT_SUCCESS(status)) { - DEBUG_ERROR("GetDriverObjectByDriverName failed with status %x", - status); + DEBUG_ERROR( + "GetDriverObjectByDriverName failed with status %x", + status); return status; } status = EnumerateDriverObjectDeviceObjects( - pci_driver_object, &pci_device_objects, &pci_device_objects_count); + pci_driver_object, + &pci_device_objects, + &pci_device_objects_count); if (!NT_SUCCESS(status)) { - DEBUG_ERROR("EnumerateDriverObjectDeviceObjects failed with status %x", - status); + DEBUG_ERROR( + "EnumerateDriverObjectDeviceObjects failed with status %x", + status); return status; } @@ -260,11 +279,11 @@ IsPciConfigurationSpaceFlagged(_In_ PPCI_COMMON_HEADER Configuration) STATIC VOID -ReportBlacklistedPcieDevice(_In_ PDEVICE_OBJECT DeviceObject, - _In_ PPCI_COMMON_HEADER Header) +ReportBlacklistedPcieDevice( + _In_ PDEVICE_OBJECT DeviceObject, _In_ PPCI_COMMON_HEADER Header) { - NTSTATUS status = STATUS_UNSUCCESSFUL; - UINT32 packet_size = CryptRequestRequiredBufferLength( + NTSTATUS status = STATUS_UNSUCCESSFUL; + UINT32 packet_size = CryptRequestRequiredBufferLength( sizeof(BLACKLISTED_PCIE_DEVICE_REPORT)); PBLACKLISTED_PCIE_DEVICE_REPORT report = @@ -276,8 +295,8 @@ ReportBlacklistedPcieDevice(_In_ PDEVICE_OBJECT DeviceObject, INIT_REPORT_PACKET(report, REPORT_BLACKLISTED_PCIE_DEVICE, 0); report->device_object = (UINT64)DeviceObject; - report->device_id = Header->DeviceID; - report->vendor_id = Header->VendorID; + report->device_id = Header->DeviceID; + report->vendor_id = Header->VendorID; status = CryptEncryptBuffer(report, packet_size); @@ -296,29 +315,35 @@ PciDeviceQueryCallback(_In_ PDEVICE_OBJECT DeviceObject, _In_opt_ PVOID Context) { UNREFERENCED_PARAMETER(Context); - NTSTATUS status = STATUS_UNSUCCESSFUL; + NTSTATUS status = STATUS_UNSUCCESSFUL; PCI_COMMON_HEADER header = {0}; status = QueryPciDeviceConfigurationSpace( - DeviceObject, PCI_VENDOR_ID_OFFSET, &header, sizeof(PCI_COMMON_HEADER)); + DeviceObject, + PCI_VENDOR_ID_OFFSET, + &header, + sizeof(PCI_COMMON_HEADER)); if (!NT_SUCCESS(status)) { - DEBUG_ERROR("QueryPciDeviceConfigurationSpace failed with status %x", - status); + DEBUG_ERROR( + "QueryPciDeviceConfigurationSpace failed with status %x", + status); return status; } if (IsPciConfigurationSpaceFlagged(&header)) { - DEBUG_VERBOSE("Flagged DeviceID found. Device: %llx, DeviceId: %lx", - (UINT64)DeviceObject, - header.DeviceID); + DEBUG_VERBOSE( + "Flagged DeviceID found. Device: %llx, DeviceId: %lx", + (UINT64)DeviceObject, + header.DeviceID); ReportBlacklistedPcieDevice(DeviceObject, &header); } else { - DEBUG_VERBOSE("Device: %llx, DeviceID: %lx, VendorID: %lx", - DeviceObject, - header.DeviceID, - header.VendorID); + DEBUG_VERBOSE( + "Device: %llx, DeviceID: %lx, VendorID: %lx", + DeviceObject, + header.DeviceID, + header.VendorID); } return status; diff --git a/driver/integrity.c b/driver/integrity.c index 47fbb4e..bf0bcc9 100644 --- a/driver/integrity.c +++ b/driver/integrity.c @@ -1,21 +1,21 @@ #include "integrity.h" -#include "common.h" -#include "driver.h" -#include "modules.h" #include "callbacks.h" -#include "io.h" +#include "common.h" +#include "crypt.h" +#include "driver.h" #include "imports.h" +#include "io.h" +#include "modules.h" +#include "pe.h" #include "session.h" #include "util.h" -#include "pe.h" -#include "crypt.h" #include "lib/stdlib.h" #include -#include #include +#include /* Header for a buffer that contains an array of sections copied from a module */ @@ -26,9 +26,9 @@ typedef struct _INTEGRITY_CHECK_HEADER { } INTEGRITY_CHECK_HEADER, *PINTEGRITY_CHECK_HEADER; typedef struct _PROCESS_MODULE_INFORMATION { - PVOID module_base; + PVOID module_base; SIZE_T module_size; - WCHAR module_path[MAX_MODULE_PATH]; + WCHAR module_path[MAX_MODULE_PATH]; } PROCESS_MODULE_INFORMATION, *PPROCESS_MODULE_INFORMATION; @@ -41,8 +41,8 @@ typedef struct _PROCESS_MODULE_VALIDATION_RESULT { typedef struct _VAL_INTEGRITY_HEADER { INTEGRITY_CHECK_HEADER integrity_check_header; - IMAGE_SECTION_HEADER section_header; - CHAR section_base[]; + IMAGE_SECTION_HEADER section_header; + CHAR section_base[]; } VAL_INTEGRITY_HEADER, *PVAL_INTEGRITY_HEADER; @@ -136,9 +136,9 @@ GetDriverImageSize(_Inout_ PIRP Irp) { PAGED_CODE(); - NTSTATUS status = STATUS_UNSUCCESSFUL; - LPCSTR driver_name = GetDriverName(); - SYSTEM_MODULES modules = {0}; + NTSTATUS status = STATUS_UNSUCCESSFUL; + LPCSTR driver_name = GetDriverName(); + SYSTEM_MODULES modules = {0}; PRTL_MODULE_EXTENDED_INFO driver_info = NULL; status = GetSystemModuleInformation(&modules); @@ -165,9 +165,10 @@ GetDriverImageSize(_Inout_ PIRP Irp) Irp->IoStatus.Information = sizeof(ULONG); - IntCopyMemory(Irp->AssociatedIrp.SystemBuffer, - &driver_info->ImageSize, - sizeof(ULONG)); + IntCopyMemory( + Irp->AssociatedIrp.SystemBuffer, + &driver_info->ImageSize, + sizeof(ULONG)); end: @@ -179,14 +180,14 @@ end: STATIC NTSTATUS -GetModuleInformationByName(_Out_ PRTL_MODULE_EXTENDED_INFO ModuleInfo, - _In_ LPCSTR ModuleName) +GetModuleInformationByName( + _Out_ PRTL_MODULE_EXTENDED_INFO ModuleInfo, _In_ LPCSTR ModuleName) { PAGED_CODE(); - NTSTATUS status = STATUS_UNSUCCESSFUL; - LPCSTR driver_name = GetDriverName(); - SYSTEM_MODULES modules = {0}; + NTSTATUS status = STATUS_UNSUCCESSFUL; + LPCSTR driver_name = GetDriverName(); + SYSTEM_MODULES modules = {0}; PRTL_MODULE_EXTENDED_INFO driver_info = NULL; status = GetSystemModuleInformation(&modules); @@ -207,12 +208,13 @@ GetModuleInformationByName(_Out_ PRTL_MODULE_EXTENDED_INFO ModuleInfo, } ModuleInfo->FileNameOffset = driver_info->FileNameOffset; - ModuleInfo->ImageBase = driver_info->ImageBase; - ModuleInfo->ImageSize = driver_info->ImageSize; + ModuleInfo->ImageBase = driver_info->ImageBase; + ModuleInfo->ImageSize = driver_info->ImageSize; - IntCopyMemory(ModuleInfo->FullPathName, - driver_info->FullPathName, - sizeof(ModuleInfo->FullPathName)); + IntCopyMemory( + ModuleInfo->FullPathName, + driver_info->FullPathName, + sizeof(ModuleInfo->FullPathName)); if (modules.address) ImpExFreePoolWithTag(modules.address, SYSTEM_MODULES_POOL); @@ -249,34 +251,36 @@ GetSectionTotalPacketSize(_In_ PIMAGE_SECTION_HEADER Section) FORCEINLINE STATIC VOID -InitIntegrityCheckHeader(_Out_ PINTEGRITY_CHECK_HEADER Header, - _In_ UINT32 SectionCount, - _In_ UINT32 TotalSize) +InitIntegrityCheckHeader( + _Out_ PINTEGRITY_CHECK_HEADER Header, + _In_ UINT32 SectionCount, + _In_ UINT32 TotalSize) { Header->section_count = SectionCount; - Header->total_size = TotalSize + sizeof(INTEGRITY_CHECK_HEADER); + Header->total_size = TotalSize + sizeof(INTEGRITY_CHECK_HEADER); } STATIC NTSTATUS -StoreModuleExecutableRegionsInBuffer(_Out_ PVOID* Buffer, - _In_ PVOID ModuleBase, - _In_ SIZE_T ModuleSize, - _Out_ PSIZE_T BytesWritten, - _In_ BOOLEAN IsModulex86) +StoreModuleExecutableRegionsInBuffer( + _Out_ PVOID* Buffer, + _In_ PVOID ModuleBase, + _In_ SIZE_T ModuleSize, + _Out_ PSIZE_T BytesWritten, + _In_ BOOLEAN IsModulex86) { PAGED_CODE(); - UINT32 total_packet_size = 0; - UINT32 num_sections = 0; - UINT32 num_executable_sections = 0; - UINT64 buffer_base = 0; - UINT32 bytes_returned = 0; - NTSTATUS status = STATUS_UNSUCCESSFUL; - PNT_HEADER_64 nt_header = NULL; - PIMAGE_SECTION_HEADER section = NULL; - MM_COPY_ADDRESS address = {0}; - INTEGRITY_CHECK_HEADER header = {0}; + UINT32 total_packet_size = 0; + UINT32 num_sections = 0; + UINT32 num_executable_sections = 0; + UINT64 buffer_base = 0; + UINT32 bytes_returned = 0; + NTSTATUS status = STATUS_UNSUCCESSFUL; + PNT_HEADER_64 nt_header = NULL; + PIMAGE_SECTION_HEADER section = NULL; + MM_COPY_ADDRESS address = {0}; + INTEGRITY_CHECK_HEADER header = {0}; if (!ModuleBase || !ModuleSize) return STATUS_INVALID_PARAMETER; @@ -292,9 +296,10 @@ StoreModuleExecutableRegionsInBuffer(_Out_ PVOID* Buffer, * the file. */ *BytesWritten = 0; - *Buffer = ImpExAllocatePool2(POOL_FLAG_NON_PAGED, - ModuleSize + sizeof(INTEGRITY_CHECK_HEADER), - POOL_TAG_INTEGRITY); + *Buffer = ImpExAllocatePool2( + POOL_FLAG_NON_PAGED, + ModuleSize + sizeof(INTEGRITY_CHECK_HEADER), + POOL_TAG_INTEGRITY); if (*Buffer == NULL) return STATUS_MEMORY_NOT_ALLOCATED; @@ -307,14 +312,14 @@ StoreModuleExecutableRegionsInBuffer(_Out_ PVOID* Buffer, * The IMAGE_DOS_HEADER.e_lfanew stores the offset of the * IMAGE_NT_HEADER from the base of the image. */ - nt_header = PeGetNtHeader(ModuleBase); + nt_header = PeGetNtHeader(ModuleBase); num_sections = GetSectionCount(nt_header); /* * The IMAGE_FIRST_SECTION macro takes in an IMAGE_NT_HEADER and returns * the address of the first section of the PE file. */ - section = IMAGE_FIRST_SECTION(nt_header); + section = IMAGE_FIRST_SECTION(nt_header); buffer_base = (UINT64)*Buffer + sizeof(INTEGRITY_CHECK_HEADER); for (UINT32 index = 0; index < num_sections - 1; index++) { @@ -324,11 +329,12 @@ StoreModuleExecutableRegionsInBuffer(_Out_ PVOID* Buffer, } address.VirtualAddress = section; - status = ImpMmCopyMemory((UINT64)buffer_base + total_packet_size, - address, - sizeof(IMAGE_SECTION_HEADER), - MM_COPY_MEMORY_VIRTUAL, - &bytes_returned); + status = ImpMmCopyMemory( + (UINT64)buffer_base + total_packet_size, + address, + sizeof(IMAGE_SECTION_HEADER), + MM_COPY_MEMORY_VIRTUAL, + &bytes_returned); if (!NT_SUCCESS(status)) { ImpExFreePoolWithTag(*Buffer, POOL_TAG_INTEGRITY); @@ -337,12 +343,13 @@ StoreModuleExecutableRegionsInBuffer(_Out_ PVOID* Buffer, } address.VirtualAddress = (UINT64)ModuleBase + section->PointerToRawData; - status = ImpMmCopyMemory((UINT64)buffer_base + total_packet_size + - sizeof(IMAGE_SECTION_HEADER), - address, - section->SizeOfRawData, - MM_COPY_MEMORY_VIRTUAL, - &bytes_returned); + status = ImpMmCopyMemory( + (UINT64)buffer_base + total_packet_size + + sizeof(IMAGE_SECTION_HEADER), + address, + section->SizeOfRawData, + MM_COPY_MEMORY_VIRTUAL, + &bytes_returned); if (!NT_SUCCESS(status)) { ImpExFreePoolWithTag(*Buffer, POOL_TAG_INTEGRITY); @@ -355,9 +362,10 @@ StoreModuleExecutableRegionsInBuffer(_Out_ PVOID* Buffer, section++; } - InitIntegrityCheckHeader(&header, - num_executable_sections, - total_packet_size); + InitIntegrityCheckHeader( + &header, + num_executable_sections, + total_packet_size); IntCopyMemory(*Buffer, &header, sizeof(INTEGRITY_CHECK_HEADER)); *BytesWritten = total_packet_size + sizeof(INTEGRITY_CHECK_HEADER); @@ -366,21 +374,22 @@ StoreModuleExecutableRegionsInBuffer(_Out_ PVOID* Buffer, STATIC NTSTATUS -MapDiskImageIntoVirtualAddressSpace(_Inout_ PHANDLE SectionHandle, - _Out_ PVOID* Section, - _In_ PUNICODE_STRING Path, - _Out_ PSIZE_T Size) +MapDiskImageIntoVirtualAddressSpace( + _Inout_ PHANDLE SectionHandle, + _Out_ PVOID* Section, + _In_ PUNICODE_STRING Path, + _Out_ PSIZE_T Size) { PAGED_CODE(); - NTSTATUS status = STATUS_UNSUCCESSFUL; - HANDLE handle = NULL; - OBJECT_ATTRIBUTES oa = {0}; - PIO_STATUS_BLOCK io = NULL; - UNICODE_STRING path = {0}; + NTSTATUS status = STATUS_UNSUCCESSFUL; + HANDLE handle = NULL; + OBJECT_ATTRIBUTES oa = {0}; + PIO_STATUS_BLOCK io = NULL; + UNICODE_STRING path = {0}; *Section = NULL; - *Size = 0; + *Size = 0; ImpRtlInitUnicodeString(&path, Path->Buffer); @@ -399,13 +408,14 @@ MapDiskImageIntoVirtualAddressSpace(_Inout_ PHANDLE SectionHandle, * Its important that we set the SEC_IMAGE flag with the PAGE_READONLY * flag as we are mapping an executable image. */ - status = ImpZwCreateSection(SectionHandle, - SECTION_ALL_ACCESS, - &oa, - NULL, - PAGE_READONLY, - SEC_IMAGE, - handle); + status = ImpZwCreateSection( + SectionHandle, + SECTION_ALL_ACCESS, + &oa, + NULL, + PAGE_READONLY, + SEC_IMAGE, + handle); if (!NT_SUCCESS(status)) { DEBUG_ERROR("ZwCreateSection failed with status %x", status); @@ -425,16 +435,17 @@ MapDiskImageIntoVirtualAddressSpace(_Inout_ PHANDLE SectionHandle, * for us, meaning the mapped image will be identical to the in memory * image. */ - status = ImpZwMapViewOfSection(*SectionHandle, - ZwCurrentProcess(), - Section, - NULL, - NULL, - NULL, - Size, - ViewUnmap, - MEM_TOP_DOWN, - PAGE_READONLY); + status = ImpZwMapViewOfSection( + *SectionHandle, + ZwCurrentProcess(), + Section, + NULL, + NULL, + NULL, + Size, + ViewUnmap, + MEM_TOP_DOWN, + PAGE_READONLY); if (!NT_SUCCESS(status)) { DEBUG_ERROR("ZwMapViewOfSection failed with status %x", status); @@ -453,11 +464,11 @@ RetrieveInMemoryModuleExecutableSections(_Inout_ PIRP Irp) { PAGED_CODE(); - NTSTATUS status = STATUS_UNSUCCESSFUL; - SIZE_T bytes_written = NULL; - PVOID buffer = NULL; - RTL_MODULE_EXTENDED_INFO module_info = {0}; - LPCSTR driver_name = GetDriverName(); + NTSTATUS status = STATUS_UNSUCCESSFUL; + SIZE_T bytes_written = NULL; + PVOID buffer = NULL; + RTL_MODULE_EXTENDED_INFO module_info = {0}; + LPCSTR driver_name = GetDriverName(); status = GetModuleInformationByName(&module_info, driver_name); @@ -466,15 +477,17 @@ RetrieveInMemoryModuleExecutableSections(_Inout_ PIRP Irp) return status; } - status = StoreModuleExecutableRegionsInBuffer(&buffer, - module_info.ImageBase, - module_info.ImageSize, - &bytes_written, - FALSE); + status = StoreModuleExecutableRegionsInBuffer( + &buffer, + module_info.ImageBase, + module_info.ImageSize, + &bytes_written, + FALSE); if (!NT_SUCCESS(status)) { - DEBUG_ERROR("StoreModuleExecutableRegionsInBuffe failed with status %x", - status); + DEBUG_ERROR( + "StoreModuleExecutableRegionsInBuffe failed with status %x", + status); return status; } @@ -523,7 +536,7 @@ GetNextSMBIOSStructureInTable(_Inout_ PSMBIOS_TABLE_HEADER* CurrentStructure) (PCHAR)((UINT64)*CurrentStructure + (*CurrentStructure)->Length); PCHAR current_char_in_strings = string_section_start; - PCHAR next_char_in_strings = string_section_start + 1; + PCHAR next_char_in_strings = string_section_start + 1; for (;;) { if (*current_char_in_strings == NULL_TERMINATOR && @@ -553,17 +566,18 @@ GetNextSMBIOSStructureInTable(_Inout_ PSMBIOS_TABLE_HEADER* CurrentStructure) */ STATIC NTSTATUS -GetStringAtIndexFromSMBIOSTable(_In_ PSMBIOS_TABLE_HEADER Table, - _In_ UINT32 Index, - _In_ PVOID Buffer, - _In_ SIZE_T BufferSize) +GetStringAtIndexFromSMBIOSTable( + _In_ PSMBIOS_TABLE_HEADER Table, + _In_ UINT32 Index, + _In_ PVOID Buffer, + _In_ SIZE_T BufferSize) { PAGED_CODE(); UINT32 current_string_char_index = 0; - UINT32 string_count = 0; - PCHAR current_string_char = (PCHAR)((UINT64)Table + Table->Length); - PCHAR next_string_char = current_string_char + 1; + UINT32 string_count = 0; + PCHAR current_string_char = (PCHAR)((UINT64)Table + Table->Length); + PCHAR next_string_char = current_string_char + 1; for (;;) { if (*current_string_char == NULL_TERMINATOR && @@ -614,20 +628,21 @@ GetSmbiosTableHeader(_In_ PRAW_SMBIOS_DATA Data) } NTSTATUS -ParseSMBIOSTable(_Out_ PVOID Buffer, - _In_ SIZE_T BufferSize, - _In_ SMBIOS_TABLE_INDEX TableIndex, - _In_ ULONG TableSubIndex) +ParseSMBIOSTable( + _Out_ PVOID Buffer, + _In_ SIZE_T BufferSize, + _In_ SMBIOS_TABLE_INDEX TableIndex, + _In_ ULONG TableSubIndex) { PAGED_CODE(); - NTSTATUS status = STATUS_UNSUCCESSFUL; - PVOID buffer = NULL; - ULONG buffer_size = 0; - ULONG bytes_copied = 0; - PRAW_SMBIOS_DATA smbios_data = NULL; - PSMBIOS_TABLE_HEADER header = NULL; - PRAW_SMBIOS_TABLE_01 baseboard = NULL; + NTSTATUS status = STATUS_UNSUCCESSFUL; + PVOID buffer = NULL; + ULONG buffer_size = 0; + ULONG bytes_copied = 0; + PRAW_SMBIOS_DATA smbios_data = NULL; + PSMBIOS_TABLE_HEADER header = NULL; + PRAW_SMBIOS_TABLE_01 baseboard = NULL; status = ImpExGetSystemFirmwareTable(SMBIOS_TABLE, 0, NULL, 0, &buffer_size); @@ -644,27 +659,30 @@ ParseSMBIOSTable(_Out_ PVOID Buffer, return STATUS_BUFFER_TOO_SMALL; } - buffer = ImpExAllocatePool2(POOL_FLAG_NON_PAGED, - buffer_size, - POOL_TAG_INTEGRITY); + buffer = ImpExAllocatePool2( + POOL_FLAG_NON_PAGED, + buffer_size, + POOL_TAG_INTEGRITY); if (!buffer) return STATUS_MEMORY_NOT_ALLOCATED; - status = ImpExGetSystemFirmwareTable(SMBIOS_TABLE, - NULL, - buffer, - buffer_size, - &bytes_copied); + status = ImpExGetSystemFirmwareTable( + SMBIOS_TABLE, + NULL, + buffer, + buffer_size, + &bytes_copied); if (!NT_SUCCESS(status)) { - DEBUG_ERROR("ExGetSystemFirmwareTable call 2 failed with status %x", - status); + DEBUG_ERROR( + "ExGetSystemFirmwareTable call 2 failed with status %x", + status); goto end; } smbios_data = GetRawSmbiosData(buffer); - header = GetSmbiosTableHeader(smbios_data); + header = GetSmbiosTableHeader(smbios_data); /* * The System Information table is equal to Type == 2 and contains the @@ -678,14 +696,16 @@ ParseSMBIOSTable(_Out_ PVOID Buffer, while (header->Type != TableIndex) GetNextSMBIOSStructureInTable(&header); - status = GetStringAtIndexFromSMBIOSTable(header, - TableSubIndex, - Buffer, - BufferSize); + status = GetStringAtIndexFromSMBIOSTable( + header, + TableSubIndex, + Buffer, + BufferSize); if (!NT_SUCCESS(status)) { - DEBUG_ERROR("GetStringAtIndexFromSMBIOSTable failed with status %x", - status); + DEBUG_ERROR( + "GetStringAtIndexFromSMBIOSTable failed with status %x", + status); goto end; } @@ -699,12 +719,13 @@ end: STATIC NTSTATUS -ComputeHashOfSections(_In_ PIMAGE_SECTION_HEADER DiskSection, - _In_ PIMAGE_SECTION_HEADER MemorySection, - _Out_ PVOID* DiskHash, - _Out_ PULONG DiskHashSize, - _Out_ PVOID* MemoryHash, - _Out_ PULONG MemoryHashSize) +ComputeHashOfSections( + _In_ PIMAGE_SECTION_HEADER DiskSection, + _In_ PIMAGE_SECTION_HEADER MemorySection, + _Out_ PVOID* DiskHash, + _Out_ PULONG DiskHashSize, + _Out_ PVOID* MemoryHash, + _Out_ PULONG MemoryHashSize) { NTSTATUS status = STATUS_UNSUCCESSFUL; @@ -750,8 +771,8 @@ STATIC VOID ReportInvalidProcessModule(_In_ PPROCESS_MODULE_INFORMATION Module) { - NTSTATUS status = STATUS_UNSUCCESSFUL; - UINT32 len = 0; + NTSTATUS status = STATUS_UNSUCCESSFUL; + UINT32 len = 0; PPROCESS_MODULE_VALIDATION_REPORT report = NULL; len = CryptRequestRequiredBufferLength( @@ -767,9 +788,10 @@ ReportInvalidProcessModule(_In_ PPROCESS_MODULE_INFORMATION Module) report->image_base = Module->module_base; report->image_size = Module->module_size; - IntCopyMemory(report->module_path, - Module->module_path, - sizeof(report->module_path)); + IntCopyMemory( + report->module_path, + Module->module_path, + sizeof(report->module_path)); status = CryptEncryptBuffer(report, len); @@ -808,22 +830,22 @@ ValidateProcessLoadedModule(_Inout_ PIRP Irp) { PAGED_CODE(); - NTSTATUS status = STATUS_UNSUCCESSFUL; + NTSTATUS status = STATUS_UNSUCCESSFUL; PROCESS_MODULE_VALIDATION_RESULT validation_result = {0}; - PPROCESS_MODULE_INFORMATION module_info = NULL; - PKPROCESS process = NULL; - KAPC_STATE apc_state = {0}; - PVAL_INTEGRITY_HEADER memory_buffer = NULL; - PVAL_INTEGRITY_HEADER disk_buffer = NULL; - PVOID memory_hash = NULL; - PVOID disk_hash = NULL; - ULONG memory_hash_size = 0; - ULONG disk_hash_size = 0; - SIZE_T bytes_written = 0; - UNICODE_STRING module_path = {0}; - HANDLE section_handle = NULL; - PVOID section = NULL; - ULONG section_size = 0; + PPROCESS_MODULE_INFORMATION module_info = NULL; + PKPROCESS process = NULL; + KAPC_STATE apc_state = {0}; + PVAL_INTEGRITY_HEADER memory_buffer = NULL; + PVAL_INTEGRITY_HEADER disk_buffer = NULL; + PVOID memory_hash = NULL; + PVOID disk_hash = NULL; + ULONG memory_hash_size = 0; + ULONG disk_hash_size = 0; + SIZE_T bytes_written = 0; + UNICODE_STRING module_path = {0}; + HANDLE section_handle = NULL; + PVOID section = NULL; + ULONG section_size = 0; status = ValidateIrpInputBuffer(Irp, sizeof(PROCESS_MODULE_INFORMATION)); @@ -842,11 +864,12 @@ ValidateProcessLoadedModule(_Inout_ PIRP Irp) */ ImpKeStackAttachProcess(process, &apc_state); - status = StoreModuleExecutableRegionsInBuffer(&memory_buffer, - module_info->module_base, - module_info->module_size, - &bytes_written, - FALSE); + status = StoreModuleExecutableRegionsInBuffer( + &memory_buffer, + module_info->module_base, + module_info->module_size, + &bytes_written, + FALSE); ImpKeUnstackDetachProcess(&apc_state); @@ -857,22 +880,25 @@ ValidateProcessLoadedModule(_Inout_ PIRP Irp) goto end; } - status = MapDiskImageIntoVirtualAddressSpace(§ion_handle, - §ion, - &module_path, - §ion_size); + status = MapDiskImageIntoVirtualAddressSpace( + §ion_handle, + §ion, + &module_path, + §ion_size); if (!NT_SUCCESS(status)) { - DEBUG_ERROR("MapDiskImageIntoVirtualAddressSpace failed with status %x", - status); + DEBUG_ERROR( + "MapDiskImageIntoVirtualAddressSpace failed with status %x", + status); goto end; } - status = StoreModuleExecutableRegionsInBuffer(&disk_buffer, - section, - section_size, - &bytes_written, - FALSE); + status = StoreModuleExecutableRegionsInBuffer( + &disk_buffer, + section, + section_size, + &bytes_written, + FALSE); if (!NT_SUCCESS(status)) { DEBUG_ERROR( @@ -881,12 +907,13 @@ ValidateProcessLoadedModule(_Inout_ PIRP Irp) goto end; } - status = ComputeHashOfSections(&memory_buffer->section_header, - &disk_buffer->section_header, - &disk_hash, - &disk_hash_size, - &memory_hash, - &memory_hash_size); + status = ComputeHashOfSections( + &memory_buffer->section_header, + &disk_buffer->section_header, + &disk_hash, + &disk_hash_size, + &memory_hash, + &memory_hash_size); if (!NT_SUCCESS(status)) { DEBUG_ERROR("ComputeHashOfSections failed with status %x", status); @@ -920,30 +947,32 @@ end: } NTSTATUS -HashUserModule(_In_ PPROCESS_MAP_MODULE_ENTRY Entry, - _Out_ PVOID OutBuffer, - _In_ UINT32 OutBufferSize) +HashUserModule( + _In_ PPROCESS_MAP_MODULE_ENTRY Entry, + _Out_ PVOID OutBuffer, + _In_ UINT32 OutBufferSize) { PAGED_CODE(); - NTSTATUS status = STATUS_UNSUCCESSFUL; - KAPC_STATE apc_state = {0}; - PVAL_INTEGRITY_HEADER memory_buffer = NULL; - PVOID memory_hash = NULL; - ULONG memory_hash_size = 0; - SIZE_T bytes_written = 0; - PACTIVE_SESSION session = GetActiveSession(); + NTSTATUS status = STATUS_UNSUCCESSFUL; + KAPC_STATE apc_state = {0}; + PVAL_INTEGRITY_HEADER memory_buffer = NULL; + PVOID memory_hash = NULL; + ULONG memory_hash_size = 0; + SIZE_T bytes_written = 0; + PACTIVE_SESSION session = GetActiveSession(); /* * Attach because the offsets given are from the process' context. */ ImpKeStackAttachProcess(session->process, &apc_state); - status = StoreModuleExecutableRegionsInBuffer(&memory_buffer, - Entry->base, - Entry->size, - &bytes_written, - FALSE); + status = StoreModuleExecutableRegionsInBuffer( + &memory_buffer, + Entry->base, + Entry->size, + &bytes_written, + FALSE); ImpKeUnstackDetachProcess(&apc_state); @@ -954,10 +983,11 @@ HashUserModule(_In_ PPROCESS_MAP_MODULE_ENTRY Entry, goto end; } - status = CryptHashBuffer_sha256(memory_buffer->section_base, - memory_buffer->section_header.SizeOfRawData, - &memory_hash, - &memory_hash_size); + status = CryptHashBuffer_sha256( + memory_buffer->section_base, + memory_buffer->section_header.SizeOfRawData, + &memory_hash, + &memory_hash_size); if (!NT_SUCCESS(status)) { DEBUG_ERROR("CryptHashBuffer_sha256 failed with status %x", status); @@ -1001,12 +1031,13 @@ GetStorageDescriptorSerialLength(_In_ PCHAR SerialNumber) FORCEINLINE STATIC VOID -InitStorageProperties(_Out_ PSTORAGE_PROPERTY_QUERY Query, - _In_ STORAGE_PROPERTY_ID PropertyId, - _In_ STORAGE_QUERY_TYPE QueryType) +InitStorageProperties( + _Out_ PSTORAGE_PROPERTY_QUERY Query, + _In_ STORAGE_PROPERTY_ID PropertyId, + _In_ STORAGE_QUERY_TYPE QueryType) { Query->PropertyId = PropertyId; - Query->QueryType = QueryType; + Query->QueryType = QueryType; } /* @@ -1014,21 +1045,21 @@ InitStorageProperties(_Out_ PSTORAGE_PROPERTY_QUERY Query, * use the command "wmic diskdrive" check in console. */ NTSTATUS -GetHardDiskDriveSerialNumber(_Inout_ PVOID ConfigDrive0Serial, - _In_ SIZE_T ConfigDrive0MaxSize) +GetHardDiskDriveSerialNumber( + _Inout_ PVOID ConfigDrive0Serial, _In_ SIZE_T ConfigDrive0MaxSize) { PAGED_CODE(); - NTSTATUS status = STATUS_UNSUCCESSFUL; - HANDLE handle = NULL; - OBJECT_ATTRIBUTES attributes = {0}; - IO_STATUS_BLOCK status_block = {0}; - STORAGE_PROPERTY_QUERY query = {0}; - STORAGE_DESCRIPTOR_HEADER header = {0}; - PSTORAGE_DEVICE_DESCRIPTOR descriptor = NULL; - UNICODE_STRING path = {0}; - PCHAR serial_number = NULL; - SIZE_T serial_length = 0; + NTSTATUS status = STATUS_UNSUCCESSFUL; + HANDLE handle = NULL; + OBJECT_ATTRIBUTES attributes = {0}; + IO_STATUS_BLOCK status_block = {0}; + STORAGE_PROPERTY_QUERY query = {0}; + STORAGE_DESCRIPTOR_HEADER header = {0}; + PSTORAGE_DEVICE_DESCRIPTOR descriptor = NULL; + UNICODE_STRING path = {0}; + PCHAR serial_number = NULL; + SIZE_T serial_length = 0; ImpRtlInitUnicodeString(&path, L"\\DosDevices\\PhysicalDrive0"); @@ -1036,67 +1067,75 @@ GetHardDiskDriveSerialNumber(_Inout_ PVOID ConfigDrive0Serial, * No need to use the flag OBJ_FORCE_ACCESS_CHECK since we arent passing * a handle given to us from usermode. */ - InitializeObjectAttributes(&attributes, - &path, - OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE, - NULL, - NULL); + InitializeObjectAttributes( + &attributes, + &path, + OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE, + NULL, + NULL); - status = ImpZwOpenFile(&handle, - GENERIC_READ, - &attributes, - &status_block, - NULL, - NULL); + status = ImpZwOpenFile( + &handle, + GENERIC_READ, + &attributes, + &status_block, + NULL, + NULL); if (!NT_SUCCESS(status)) { - DEBUG_ERROR("ZwOpenFile on PhysicalDrive0 failed with status %x", - status); + DEBUG_ERROR( + "ZwOpenFile on PhysicalDrive0 failed with status %x", + status); goto end; } InitStorageProperties(&query, StorageDeviceProperty, PropertyStandardQuery); - status = ImpZwDeviceIoControlFile(handle, - NULL, - NULL, - NULL, - &status_block, - IOCTL_STORAGE_QUERY_PROPERTY, - &query, - sizeof(STORAGE_PROPERTY_QUERY), - &header, - sizeof(STORAGE_DESCRIPTOR_HEADER)); + status = ImpZwDeviceIoControlFile( + handle, + NULL, + NULL, + NULL, + &status_block, + IOCTL_STORAGE_QUERY_PROPERTY, + &query, + sizeof(STORAGE_PROPERTY_QUERY), + &header, + sizeof(STORAGE_DESCRIPTOR_HEADER)); if (!NT_SUCCESS(status)) { - DEBUG_ERROR("ZwDeviceIoControlFile first call failed with status %x", - status); + DEBUG_ERROR( + "ZwDeviceIoControlFile first call failed with status %x", + status); goto end; } - descriptor = ImpExAllocatePool2(POOL_FLAG_NON_PAGED, - header.Size, - POOL_TAG_INTEGRITY); + descriptor = ImpExAllocatePool2( + POOL_FLAG_NON_PAGED, + header.Size, + POOL_TAG_INTEGRITY); if (!descriptor) { status = STATUS_MEMORY_NOT_ALLOCATED; goto end; } - status = ImpZwDeviceIoControlFile(handle, - NULL, - NULL, - NULL, - &status_block, - IOCTL_STORAGE_QUERY_PROPERTY, - &query, - sizeof(STORAGE_PROPERTY_QUERY), - descriptor, - header.Size); + status = ImpZwDeviceIoControlFile( + handle, + NULL, + NULL, + NULL, + &status_block, + IOCTL_STORAGE_QUERY_PROPERTY, + &query, + sizeof(STORAGE_PROPERTY_QUERY), + descriptor, + header.Size); if (!NT_SUCCESS(status)) { - DEBUG_ERROR("ZwDeviceIoControlFile second call failed with status %x", - status); + DEBUG_ERROR( + "ZwDeviceIoControlFile second call failed with status %x", + status); goto end; } @@ -1124,19 +1163,20 @@ end: return status; } PVOID -ScanForSignature(_In_ PVOID BaseAddress, - _In_ SIZE_T MaxLength, - _In_ LPCSTR Signature, - _In_ SIZE_T SignatureLength) +ScanForSignature( + _In_ PVOID BaseAddress, + _In_ SIZE_T MaxLength, + _In_ LPCSTR Signature, + _In_ SIZE_T SignatureLength) { PAGED_CODE(); - CHAR current_char = 0; + CHAR current_char = 0; CHAR current_sig_char = 0; for (INT index = 0; index < MaxLength; index++) { for (INT sig = 0; sig < SignatureLength + 1; sig++) { - current_char = *(PCHAR)((UINT64)BaseAddress + index + sig); + current_char = *(PCHAR)((UINT64)BaseAddress + index + sig); current_sig_char = Signature[sig]; if (sig == SignatureLength) @@ -1160,7 +1200,7 @@ UINT64 MeasureInstructionRead(_In_ PVOID InstructionAddress) { CONST UINT64 start = __readmsr(IA32_APERF_MSR) << 32; - CHAR value = *(PCHAR)InstructionAddress; + CHAR value = *(PCHAR)InstructionAddress; return (__readmsr(IA32_APERF_MSR) << 32) - start; } @@ -1171,7 +1211,7 @@ UINT64 MeasureReads(_In_ PVOID Address, _In_ ULONG Count) { UINT64 read_average = 0; - KIRQL irql = {0}; + KIRQL irql = {0}; MeasureInstructionRead(Address); @@ -1210,8 +1250,8 @@ MeasureReads(_In_ PVOID Address, _In_ ULONG Count) */ STATIC NTSTATUS -GetAverageReadTimeAtRoutine(_In_ PVOID RoutineAddress, - _Out_ PUINT64 AverageTime) +GetAverageReadTimeAtRoutine( + _In_ PVOID RoutineAddress, _Out_ PUINT64 AverageTime) { if (!RoutineAddress || !AverageTime) return STATUS_UNSUCCESSFUL; @@ -1302,16 +1342,17 @@ InitiateEptFunctionAddressArrays() STATIC VOID -ReportEptHook(_In_ UINT64 ControlAverage, - _In_ UINT64 ReadAverage, - _In_ WCHAR FunctionName) +ReportEptHook( + _In_ UINT64 ControlAverage, + _In_ UINT64 ReadAverage, + _In_ WCHAR FunctionName) { - NTSTATUS status = STATUS_UNSUCCESSFUL; - UINT32 len = 0; + NTSTATUS status = STATUS_UNSUCCESSFUL; + UINT32 len = 0; PEPT_HOOK_REPORT report = NULL; - UNICODE_STRING string = {0}; + UNICODE_STRING string = {0}; - len = CryptRequestRequiredBufferLength(sizeof(EPT_HOOK_REPORT)); + len = CryptRequestRequiredBufferLength(sizeof(EPT_HOOK_REPORT)); report = ImpExAllocatePool2(POOL_FLAG_NON_PAGED, len, REPORT_POOL_TAG); if (!report) @@ -1320,13 +1361,14 @@ ReportEptHook(_In_ UINT64 ControlAverage, INIT_REPORT_PACKET(report, REPORT_EPT_HOOK, 0); report->control_average = ControlAverage; - report->read_average = ReadAverage; + report->read_average = ReadAverage; RtlInitUnicodeString(&string, FunctionName); - status = UnicodeToCharBufString(&string, - report->function_name, - sizeof(report->function_name)); + status = UnicodeToCharBufString( + &string, + report->function_name, + sizeof(report->function_name)); if (!NT_SUCCESS(status)) DEBUG_ERROR("UnicodeToCharBufString: %x", status); @@ -1347,29 +1389,32 @@ DetectEptHooksInKeyFunctions() { PAGED_CODE(); - NTSTATUS status = STATUS_UNSUCCESSFUL; - UINT32 control_fails = 0; - UINT64 instruction_time = 0; - UINT64 control_time_sum = 0; - UINT64 control_average = 0; + NTSTATUS status = STATUS_UNSUCCESSFUL; + UINT32 control_fails = 0; + UINT64 instruction_time = 0; + UINT64 control_time_sum = 0; + UINT64 control_average = 0; /* todo: once we call this, we need to set a flag to skip this, * otherwise we just return early */ status = InitiateEptFunctionAddressArrays(); if (!NT_SUCCESS(status)) { - DEBUG_ERROR("InitiateEptFunctionAddressArrays failed with status %x", - status); + DEBUG_ERROR( + "InitiateEptFunctionAddressArrays failed with status %x", + status); return status; } for (UINT32 index = 0; index < EPT_CONTROL_FUNCTIONS_COUNT; index++) { - status = GetAverageReadTimeAtRoutine(CONTROL_FUNCTION_ADDRESSES[index], - &instruction_time); + status = GetAverageReadTimeAtRoutine( + CONTROL_FUNCTION_ADDRESSES[index], + &instruction_time); if (!NT_SUCCESS(status)) { - DEBUG_ERROR("DetectEptPresentOnFunction failed with status %x", - status); + DEBUG_ERROR( + "DetectEptPresentOnFunction failed with status %x", + status); control_fails += 1; continue; } @@ -1387,13 +1432,14 @@ DetectEptHooksInKeyFunctions() return STATUS_UNSUCCESSFUL; for (UINT32 index = 0; index < EPT_PROTECTED_FUNCTIONS_COUNT; index++) { - status = - GetAverageReadTimeAtRoutine(PROTECTED_FUNCTION_ADDRESSES[index], - &instruction_time); + status = GetAverageReadTimeAtRoutine( + PROTECTED_FUNCTION_ADDRESSES[index], + &instruction_time); if (!NT_SUCCESS(status)) { - DEBUG_ERROR("DetectEptPresentOnFunction failed with status %x", - status); + DEBUG_ERROR( + "DetectEptPresentOnFunction failed with status %x", + status); continue; } @@ -1405,9 +1451,10 @@ DetectEptHooksInKeyFunctions() "EPT hook detected at function: %llx with execution time of: %llx", PROTECTED_FUNCTION_ADDRESSES[index], instruction_time); - ReportEptHook(control_average, - instruction_time, - PROTECTED_FUNCTION_ADDRESSES[index]); + ReportEptHook( + control_average, + instruction_time, + PROTECTED_FUNCTION_ADDRESSES[index]); } } @@ -1417,8 +1464,8 @@ DetectEptHooksInKeyFunctions() VOID FindWinLogonProcess(_In_ PPROCESS_LIST_ENTRY Node, _In_opt_ PVOID Context) { - LPCSTR process_name = NULL; - PEPROCESS* process = (PEPROCESS*)Context; + LPCSTR process_name = NULL; + PEPROCESS* process = (PEPROCESS*)Context; if (!Context) return; @@ -1431,12 +1478,13 @@ FindWinLogonProcess(_In_ PPROCESS_LIST_ENTRY Node, _In_opt_ PVOID Context) STATIC NTSTATUS -StoreModuleExecutableRegionsx86(_In_ PRTL_MODULE_EXTENDED_INFO Module, - _In_ PVOID* Buffer, - _In_ PULONG BufferSize) +StoreModuleExecutableRegionsx86( + _In_ PRTL_MODULE_EXTENDED_INFO Module, + _In_ PVOID* Buffer, + _In_ PULONG BufferSize) { - NTSTATUS status = STATUS_UNSUCCESSFUL; - PEPROCESS process = NULL; + NTSTATUS status = STATUS_UNSUCCESSFUL; + PEPROCESS process = NULL; KAPC_STATE apc_state = {0}; RtlHashmapEnumerate(GetProcessHashmap(), FindWinLogonProcess, &process); @@ -1446,11 +1494,12 @@ StoreModuleExecutableRegionsx86(_In_ PRTL_MODULE_EXTENDED_INFO Module, ImpKeStackAttachProcess(process, &apc_state); - status = StoreModuleExecutableRegionsInBuffer(Buffer, - Module->ImageBase, - Module->ImageSize, - BufferSize, - TRUE); + status = StoreModuleExecutableRegionsInBuffer( + Buffer, + Module->ImageBase, + Module->ImageSize, + BufferSize, + TRUE); ImpKeUnstackDetachProcess(&apc_state); @@ -1471,18 +1520,18 @@ Enablex86Hashing(_In_ PDRIVER_LIST_HEAD Head) } VOID -DeferredModuleHashingCallback(_In_ PDEVICE_OBJECT DeviceObject, - _In_opt_ PVOID Context) +DeferredModuleHashingCallback( + _In_ PDEVICE_OBJECT DeviceObject, _In_opt_ PVOID Context) { UNREFERENCED_PARAMETER(Context); UNREFERENCED_PARAMETER(DeviceObject); - NTSTATUS status = STATUS_UNSUCCESSFUL; + NTSTATUS status = STATUS_UNSUCCESSFUL; RTL_MODULE_EXTENDED_INFO module = {0}; - PDRIVER_LIST_HEAD list = GetDriverList(); - PLIST_ENTRY head = &GetDriverList()->deferred_list; - PLIST_ENTRY entry = NULL; - PDRIVER_LIST_ENTRY driver = NULL; + PDRIVER_LIST_HEAD list = GetDriverList(); + PLIST_ENTRY head = &GetDriverList()->deferred_list; + PLIST_ENTRY entry = NULL; + PDRIVER_LIST_ENTRY driver = NULL; Enablex86Hashing(list); @@ -1503,12 +1552,12 @@ DeferredModuleHashingCallback(_In_ PDEVICE_OBJECT DeviceObject, if (!NT_SUCCESS(status)) { DEBUG_ERROR("HashModule-x86 failed with status %x", status); driver->hashed = FALSE; - entry = RemoveHeadList(head); + entry = RemoveHeadList(head); continue; } driver->hashed = TRUE; - entry = RemoveHeadList(head); + entry = RemoveHeadList(head); } end: @@ -1521,15 +1570,15 @@ end: NTSTATUS HashModule(_In_ PRTL_MODULE_EXTENDED_INFO Module, _Out_ PVOID Hash) { - NTSTATUS status = STATUS_UNSUCCESSFUL; - ANSI_STRING ansi_string = {0}; - UNICODE_STRING path = {0}; - ULONG memory_text_size = 0; - PVOID memory_hash = NULL; - ULONG memory_hash_size = 0; - PVAL_INTEGRITY_HEADER memory_buffer = NULL; - ULONG memory_buffer_size = 0; - PDRIVER_LIST_HEAD list = GetDriverList(); + NTSTATUS status = STATUS_UNSUCCESSFUL; + ANSI_STRING ansi_string = {0}; + UNICODE_STRING path = {0}; + ULONG memory_text_size = 0; + PVOID memory_hash = NULL; + ULONG memory_hash_size = 0; + PVAL_INTEGRITY_HEADER memory_buffer = NULL; + ULONG memory_buffer_size = 0; + PDRIVER_LIST_HEAD list = GetDriverList(); ImpRtlInitAnsiString(&ansi_string, Module->FullPathName); @@ -1541,8 +1590,9 @@ HashModule(_In_ PRTL_MODULE_EXTENDED_INFO Module, _Out_ PVOID Hash) status = ImpRtlAnsiStringToUnicodeString(&path, &ansi_string, TRUE); if (!NT_SUCCESS(status)) { - DEBUG_ERROR("RtlAnsiStringToUnicodeString failed with status %x", - status); + DEBUG_ERROR( + "RtlAnsiStringToUnicodeString failed with status %x", + status); return status; } @@ -1568,16 +1618,18 @@ HashModule(_In_ PRTL_MODULE_EXTENDED_INFO Module, _Out_ PVOID Hash) * Once the WinLogon process has started, we can then hash new * x86 modules. */ - status = StoreModuleExecutableRegionsx86(Module, - (PVOID)&memory_buffer, - &memory_buffer_size); + status = StoreModuleExecutableRegionsx86( + Module, + (PVOID)&memory_buffer, + &memory_buffer_size); } else { - status = StoreModuleExecutableRegionsInBuffer((PVOID)&memory_buffer, - Module->ImageBase, - Module->ImageSize, - &memory_buffer_size, - FALSE); + status = StoreModuleExecutableRegionsInBuffer( + (PVOID)&memory_buffer, + Module->ImageBase, + Module->ImageSize, + &memory_buffer_size, + FALSE); } if (!NT_SUCCESS(status)) { @@ -1587,10 +1639,11 @@ HashModule(_In_ PRTL_MODULE_EXTENDED_INFO Module, _Out_ PVOID Hash) goto end; } - status = CryptHashBuffer_sha256(memory_buffer->section_base, - memory_buffer->section_header.SizeOfRawData, - &memory_hash, - &memory_hash_size); + status = CryptHashBuffer_sha256( + memory_buffer->section_base, + memory_buffer->section_header.SizeOfRawData, + &memory_hash, + &memory_hash_size); if (!NT_SUCCESS(status)) { DEBUG_VERBOSE("ComputeHashOfSections failed with status %x", status); @@ -1622,8 +1675,8 @@ STATIC VOID ReportModifiedSystemImage(_In_ PRTL_MODULE_EXTENDED_INFO Module) { - NTSTATUS status = STATUS_UNSUCCESSFUL; - UINT32 len = 0; + NTSTATUS status = STATUS_UNSUCCESSFUL; + UINT32 len = 0; PSYSTEM_MODULE_INTEGRITY_CHECK_REPORT report = NULL; len = CryptRequestRequiredBufferLength( @@ -1639,9 +1692,10 @@ ReportModifiedSystemImage(_In_ PRTL_MODULE_EXTENDED_INFO Module) report->image_base = Module->ImageBase; report->image_size = Module->ImageSize; - IntCopyMemory(report->path_name, - Module->FullPathName, - sizeof(report->path_name)); + IntCopyMemory( + report->path_name, + Module->FullPathName, + sizeof(report->path_name)); status = CryptEncryptBuffer(report, len); @@ -1657,13 +1711,14 @@ ReportModifiedSystemImage(_In_ PRTL_MODULE_EXTENDED_INFO Module) VOID ValidateSystemModule(_In_ PRTL_MODULE_EXTENDED_INFO Module) { - NTSTATUS status = STATUS_UNSUCCESSFUL; - PDRIVER_LIST_ENTRY entry = NULL; - PVOID hash = NULL; + NTSTATUS status = STATUS_UNSUCCESSFUL; + PDRIVER_LIST_ENTRY entry = NULL; + PVOID hash = NULL; - hash = ExAllocatePool2(POOL_FLAG_NON_PAGED, - SHA_256_HASH_LENGTH, - POOL_TAG_INTEGRITY); + hash = ExAllocatePool2( + POOL_FLAG_NON_PAGED, + SHA_256_HASH_LENGTH, + POOL_TAG_INTEGRITY); if (!hash) return; @@ -1698,12 +1753,14 @@ ValidateSystemModule(_In_ PRTL_MODULE_EXTENDED_INFO Module) } if (CompareHashes(hash, entry->text_hash, SHA_256_HASH_LENGTH)) { - DEBUG_VERBOSE("Module: %s text regions are valid.", - Module->FullPathName); + DEBUG_VERBOSE( + "Module: %s text regions are valid.", + Module->FullPathName); } else { - DEBUG_WARNING("**!!** Module: %s text regions are NOT valid **!!**", - Module->FullPathName); + DEBUG_WARNING( + "**!!** Module: %s text regions are NOT valid **!!**", + Module->FullPathName); ReportModifiedSystemImage(Module); } @@ -1717,8 +1774,8 @@ STATIC VOID ReportModifiedSelfDriverImage(_In_ PRTL_MODULE_EXTENDED_INFO Module) { - NTSTATUS status = STATUS_UNSUCCESSFUL; - UINT32 len = 0; + NTSTATUS status = STATUS_UNSUCCESSFUL; + UINT32 len = 0; PDRIVER_SELF_INTEGRITY_CHECK_REPORT packet = NULL; len = CryptRequestRequiredBufferLength( @@ -1734,9 +1791,10 @@ ReportModifiedSelfDriverImage(_In_ PRTL_MODULE_EXTENDED_INFO Module) packet->image_base = Module->ImageBase; packet->image_size = Module->ImageSize; - IntCopyMemory(packet->path_name, - Module->FullPathName, - sizeof(packet->path_name)); + IntCopyMemory( + packet->path_name, + Module->FullPathName, + sizeof(packet->path_name)); status = CryptEncryptBuffer(packet, len); @@ -1752,14 +1810,14 @@ ReportModifiedSelfDriverImage(_In_ PRTL_MODULE_EXTENDED_INFO Module) NTSTATUS ValidateOurDriverImage() { - NTSTATUS status = STATUS_UNSUCCESSFUL; - SYSTEM_MODULES modules = {0}; - PRTL_MODULE_EXTENDED_INFO module_info = NULL; - PVOID memory_hash = NULL; - ULONG memory_hash_size = 0; - PDRIVER_LIST_ENTRY entry = NULL; - LPCSTR driver_name = GetDriverName(); - PUNICODE_STRING path = GetDriverPath(); + NTSTATUS status = STATUS_UNSUCCESSFUL; + SYSTEM_MODULES modules = {0}; + PRTL_MODULE_EXTENDED_INFO module_info = NULL; + PVOID memory_hash = NULL; + ULONG memory_hash_size = 0; + PDRIVER_LIST_ENTRY entry = NULL; + LPCSTR driver_name = GetDriverName(); + PUNICODE_STRING path = GetDriverPath(); status = GetSystemModuleInformation(&modules); @@ -1775,9 +1833,10 @@ ValidateOurDriverImage() goto end; } - memory_hash = ExAllocatePool2(POOL_FLAG_NON_PAGED, - SHA_256_HASH_LENGTH, - POOL_TAG_INTEGRITY); + memory_hash = ExAllocatePool2( + POOL_FLAG_NON_PAGED, + SHA_256_HASH_LENGTH, + POOL_TAG_INTEGRITY); if (!memory_hash) goto end; @@ -1861,8 +1920,8 @@ GetCurrentVerificationIndex(_In_ PSYS_MODULE_VAL_CONTEXT Context) FORCEINLINE STATIC UINT32 -GetCurrentVerificationMaxIndex(_In_ PSYS_MODULE_VAL_CONTEXT Context, - _In_ UINT32 Count) +GetCurrentVerificationMaxIndex( + _In_ PSYS_MODULE_VAL_CONTEXT Context, _In_ UINT32 Count) { return Count + Context->block_size; } @@ -1870,21 +1929,21 @@ GetCurrentVerificationMaxIndex(_In_ PSYS_MODULE_VAL_CONTEXT Context, FORCEINLINE STATIC VOID -UpdateCurrentVerificationIndex(_In_ PSYS_MODULE_VAL_CONTEXT Context, - _In_ UINT32 Count) +UpdateCurrentVerificationIndex( + _In_ PSYS_MODULE_VAL_CONTEXT Context, _In_ UINT32 Count) { InterlockedExchange(&Context->current_count, Count); } STATIC VOID -SystemModuleVerificationDispatchFunction(_In_ PDEVICE_OBJECT DeviceObject, - _In_ PSYS_MODULE_VAL_CONTEXT Context) +SystemModuleVerificationDispatchFunction( + _In_ PDEVICE_OBJECT DeviceObject, _In_ PSYS_MODULE_VAL_CONTEXT Context) { UNREFERENCED_PARAMETER(DeviceObject); UINT32 count = 0; - UINT32 max = 0; + UINT32 max = 0; IncrementActiveThreadCount(Context); @@ -1920,17 +1979,18 @@ SystemModuleVerificationDispatchFunction(_In_ PDEVICE_OBJECT DeviceObject, FORCEINLINE STATIC VOID -InitSysModuleValidationContext(_Out_ PSYS_MODULE_VAL_CONTEXT Context, - _In_ PMODULE_DISPATCHER_HEADER DispatcherArray, - _In_ PSYSTEM_MODULES SystemModules) +InitSysModuleValidationContext( + _Out_ PSYS_MODULE_VAL_CONTEXT Context, + _In_ PMODULE_DISPATCHER_HEADER DispatcherArray, + _In_ PSYSTEM_MODULES SystemModules) { Context->active_thread_count = 0; - Context->active = TRUE; - Context->complete = FALSE; - Context->dispatcher_info = DispatcherArray; - Context->module_info = SystemModules->address; - Context->total_count = SystemModules->module_count; - Context->block_size = VALIDATION_BLOCK_SIZE; + Context->active = TRUE; + Context->complete = FALSE; + Context->dispatcher_info = DispatcherArray; + Context->module_info = SystemModules->address; + Context->total_count = SystemModules->module_count; + Context->block_size = VALIDATION_BLOCK_SIZE; /* skip hal.dll and ntosrnl.exe */ Context->current_count = 2; @@ -1951,10 +2011,10 @@ STATIC NTSTATUS InitialiseSystemModuleVerificationContext(PSYS_MODULE_VAL_CONTEXT Context) { - NTSTATUS status = STATUS_UNSUCCESSFUL; - SYSTEM_MODULES modules = {0}; + NTSTATUS status = STATUS_UNSUCCESSFUL; + SYSTEM_MODULES modules = {0}; PMODULE_DISPATCHER_HEADER dispatcher = NULL; - UINT32 count = 0; + UINT32 count = 0; status = GetSystemModuleInformation(&modules); @@ -2013,7 +2073,7 @@ FreeModuleVerificationItems(_In_ PSYS_MODULE_VAL_CONTEXT Context) VOID CleanupValidationContextOnUnload(_In_ PSYS_MODULE_VAL_CONTEXT Context) { - Context->active = FALSE; + Context->active = FALSE; Context->complete = TRUE; FreeWorkItems(Context); FreeModuleVerificationItems(Context); @@ -2030,25 +2090,26 @@ DispatchVerificationWorkerThreads(_In_ PSYS_MODULE_VAL_CONTEXT Context) if (!Context->work_items[index]) continue; - ImpIoQueueWorkItem(Context->work_items[index], - SystemModuleVerificationDispatchFunction, - DelayedWorkQueue, - Context); + ImpIoQueueWorkItem( + Context->work_items[index], + SystemModuleVerificationDispatchFunction, + DelayedWorkQueue, + Context); } } NTSTATUS SystemModuleVerificationDispatcher() { - NTSTATUS status = STATUS_UNSUCCESSFUL; - PIO_WORKITEM work_item = NULL; - PSYS_MODULE_VAL_CONTEXT context = GetSystemModuleValidationContext(); + NTSTATUS status = STATUS_UNSUCCESSFUL; + PIO_WORKITEM work_item = NULL; + PSYS_MODULE_VAL_CONTEXT context = GetSystemModuleValidationContext(); if (context->complete) { DEBUG_VERBOSE( "System modules integrity check complete. Freeing items."); - context->active = FALSE; + context->active = FALSE; context->complete = FALSE; FreeModuleVerificationItems(context); @@ -2083,8 +2144,8 @@ SystemModuleVerificationDispatcher() NTSTATUS GetOsVersionInformation(_Out_ PRTL_OSVERSIONINFOW VersionInfo) { - NTSTATUS status = STATUS_ABANDONED; - RTL_OSVERSIONINFOW info = {0}; + NTSTATUS status = STATUS_ABANDONED; + RTL_OSVERSIONINFOW info = {0}; if (!VersionInfo) return STATUS_INVALID_PARAMETER; @@ -2096,15 +2157,16 @@ GetOsVersionInformation(_Out_ PRTL_OSVERSIONINFOW VersionInfo) return status; } - VersionInfo->dwBuildNumber = info.dwBuildNumber; - VersionInfo->dwMajorVersion = info.dwMajorVersion; - VersionInfo->dwMinorVersion = info.dwMinorVersion; + VersionInfo->dwBuildNumber = info.dwBuildNumber; + VersionInfo->dwMajorVersion = info.dwMajorVersion; + VersionInfo->dwMinorVersion = info.dwMinorVersion; VersionInfo->dwOSVersionInfoSize = info.dwOSVersionInfoSize; - VersionInfo->dwPlatformId = info.dwPlatformId; + VersionInfo->dwPlatformId = info.dwPlatformId; - IntCopyMemory(VersionInfo->szCSDVersion, - info.szCSDVersion, - sizeof(VersionInfo->szCSDVersion)); + IntCopyMemory( + VersionInfo->szCSDVersion, + info.szCSDVersion, + sizeof(VersionInfo->szCSDVersion)); return status; } @@ -2118,28 +2180,29 @@ GetOsVersionInformation(_Out_ PRTL_OSVERSIONINFOW VersionInfo) UINT32 CalculateCpuCoreUsage(_In_ UINT32 Core) { - PVOID kpcr = NULL; - PVOID kpcrb = NULL; - PVOID idle_thread = NULL; - UINT32 idle_time = 0; + PVOID kpcr = NULL; + PVOID kpcrb = NULL; + PVOID idle_thread = NULL; + UINT32 idle_time = 0; UINT32 kernel_time = 0; - UINT32 user_time = 0; + UINT32 user_time = 0; KeSetSystemAffinityThread(1ull << Core); while (Core != KeGetCurrentProcessorNumber()) YieldProcessor(); - kpcr = __readmsr(IA32_GS_BASE); - kpcrb = (UINT64)kpcr + KPCR_KPRCB_OFFSET; + kpcr = __readmsr(IA32_GS_BASE); + kpcrb = (UINT64)kpcr + KPCR_KPRCB_OFFSET; idle_thread = *(UINT64*)((UINT64)kpcrb + KPCRB_IDLE_THREAD_OFFSET); - idle_time = *(UINT32*)((UINT64)idle_thread + KTHREAD_IDLE_TIME_OFFSET); + idle_time = *(UINT32*)((UINT64)idle_thread + KTHREAD_IDLE_TIME_OFFSET); kernel_time = *(UINT32*)((UINT64)kpcrb + KPCRB_KERNEL_TIME_OFFSET); - user_time = *(UINT32*)((UINT64)kpcrb + KPCRB_USER_TIME_OFFSET); + user_time = *(UINT32*)((UINT64)kpcrb + KPCRB_USER_TIME_OFFSET); - return (100 - (UINT32)(UInt32x32To64(idle_time, 100) / - (UINT64)(kernel_time + user_time))); + return ( + 100 - (UINT32)(UInt32x32To64(idle_time, 100) / + (UINT64)(kernel_time + user_time))); } BOOLEAN @@ -2177,16 +2240,18 @@ STATIC NTSTATUS AllocateHeartbeatObjects(_Inout_ PHEARTBEAT_CONFIGURATION Configuration) { - Configuration->dpc = ImpExAllocatePool2(POOL_FLAG_NON_PAGED, - sizeof(KDPC), - POOL_TAG_HEARTBEAT); + Configuration->dpc = ImpExAllocatePool2( + POOL_FLAG_NON_PAGED, + sizeof(KDPC), + POOL_TAG_HEARTBEAT); if (!Configuration->dpc) return STATUS_INSUFFICIENT_RESOURCES; - Configuration->timer = ImpExAllocatePool2(POOL_FLAG_NON_PAGED, - sizeof(KTIMER), - POOL_TAG_HEARTBEAT); + Configuration->timer = ImpExAllocatePool2( + POOL_FLAG_NON_PAGED, + sizeof(KTIMER), + POOL_TAG_HEARTBEAT); if (!Configuration->timer) { ImpExFreePoolWithTag(Configuration->dpc, POOL_TAG_HEARTBEAT); @@ -2209,8 +2274,8 @@ STATIC LARGE_INTEGER GenerateHeartbeatDueTime() { - UINT64 interval = 0; - LARGE_INTEGER ticks = {0}; + UINT64 interval = 0; + LARGE_INTEGER ticks = {0}; LARGE_INTEGER due_time = {0}; KeQueryTickCount(&ticks); @@ -2272,7 +2337,7 @@ STATIC PHEARTBEAT_PACKET BuildHeartbeatPacket(_In_ UINT32 Size) { - PIRP_QUEUE_HEAD queue = GetIrpQueueHead(); + PIRP_QUEUE_HEAD queue = GetIrpQueueHead(); PHEARTBEAT_PACKET packet = NULL; packet = ImpExAllocatePool2(POOL_FLAG_NON_PAGED, Size, POOL_TAG_HEARTBEAT); @@ -2290,8 +2355,8 @@ BuildHeartbeatPacket(_In_ UINT32 Size) * less then whats noted. */ packet->total_heartbeats_completed = queue->total_heartbeats_completed; - packet->total_irps_completed = queue->total_irps_completed; - packet->total_reports_completed = queue->total_reports_completed; + packet->total_irps_completed = queue->total_irps_completed; + packet->total_reports_completed = queue->total_reports_completed; KeReleaseGuardedMutex(&queue->lock); @@ -2307,17 +2372,17 @@ HeartbeatWorkItem(_In_ PDEVICE_OBJECT DeviceObject, _In_opt_ PVOID Context) if (!ARGUMENT_PRESENT(Context)) return; - UINT32 packet_size = 0; - NTSTATUS status = STATUS_UNSUCCESSFUL; - PHEARTBEAT_PACKET packet = NULL; - PHEARTBEAT_CONFIGURATION config = (PHEARTBEAT_CONFIGURATION)Context; + UINT32 packet_size = 0; + NTSTATUS status = STATUS_UNSUCCESSFUL; + PHEARTBEAT_PACKET packet = NULL; + PHEARTBEAT_CONFIGURATION config = (PHEARTBEAT_CONFIGURATION)Context; DEBUG_VERBOSE("Heartbeat timer alerted. Generating heartbeat packet."); SetHeartbeatActive(config); packet_size = CryptRequestRequiredBufferLength(sizeof(HEARTBEAT_PACKET)); - packet = BuildHeartbeatPacket(packet_size); + packet = BuildHeartbeatPacket(packet_size); if (packet) { status = CryptEncryptBuffer(packet, packet_size); @@ -2350,10 +2415,11 @@ queue_next: STATIC VOID -HeartbeatDpcRoutine(_In_ PKDPC Dpc, - _In_opt_ PVOID DeferredContext, - _In_opt_ PVOID SystemArgument1, - _In_opt_ PVOID SystemArgument2) +HeartbeatDpcRoutine( + _In_ PKDPC Dpc, + _In_opt_ PVOID DeferredContext, + _In_opt_ PVOID SystemArgument1, + _In_opt_ PVOID SystemArgument2) { UNREFERENCED_PARAMETER(Dpc); UNREFERENCED_PARAMETER(SystemArgument1); @@ -2364,10 +2430,11 @@ HeartbeatDpcRoutine(_In_ PKDPC Dpc, PHEARTBEAT_CONFIGURATION config = (PHEARTBEAT_CONFIGURATION)DeferredContext; - IoQueueWorkItem(config->work_item, - HeartbeatWorkItem, - NormalWorkQueue, - config); + IoQueueWorkItem( + config->work_item, + HeartbeatWorkItem, + NormalWorkQueue, + config); } /* @@ -2389,9 +2456,9 @@ InitialiseHeartbeatConfiguration(_Out_ PHEARTBEAT_CONFIGURATION Configuration) { NTSTATUS status = STATUS_UNSUCCESSFUL; - Configuration->counter = 0; - Configuration->active = FALSE; - Configuration->seed = GenerateRandSeed(); + Configuration->counter = 0; + Configuration->active = FALSE; + Configuration->seed = GenerateRandSeed(); Configuration->work_item = IoAllocateWorkItem(GetDriverDeviceObject()); if (!Configuration->work_item) diff --git a/driver/io.c b/driver/io.c index 6023793..c1a9d2a 100644 --- a/driver/io.c +++ b/driver/io.c @@ -1,18 +1,18 @@ #include "io.h" -#include "modules.h" -#include "driver.h" #include "callbacks.h" -#include "pool.h" +#include "driver.h" #include "integrity.h" +#include "modules.h" +#include "pool.h" #include "thread.h" #include "hv.h" #include "imports.h" -#include "session.h" -#include "hw.h" #include "containers/map.h" +#include "hw.h" +#include "session.h" #include "lib/stdlib.h" @@ -171,9 +171,9 @@ STATIC NTSTATUS IrpQueueCompleteDeferredPacket(_In_ PDEFERRED_REPORT Report, _In_ PIRP Irp) { - NTSTATUS status = ValidateIrpOutputBuffer(Irp, Report->buffer_size); - PIRP_QUEUE_HEAD queue = GetIrpQueueHead(); - UINT16 type = GetPacketType(Report->buffer); + NTSTATUS status = ValidateIrpOutputBuffer(Irp, Report->buffer_size); + PIRP_QUEUE_HEAD queue = GetIrpQueueHead(); + UINT16 type = GetPacketType(Report->buffer); if (!NT_SUCCESS(status)) return status; @@ -181,9 +181,11 @@ IrpQueueCompleteDeferredPacket(_In_ PDEFERRED_REPORT Report, _In_ PIRP Irp) IncrementPacketMetics(queue, type); IntCopyMemory( - Irp->AssociatedIrp.SystemBuffer, Report->buffer, Report->buffer_size); + Irp->AssociatedIrp.SystemBuffer, + Report->buffer, + Report->buffer_size); - Irp->IoStatus.Status = STATUS_SUCCESS; + Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = Report->buffer_size; IofCompleteRequest(Irp, IO_NO_INCREMENT); IrpQueueFreeDeferredPacket(Report); @@ -194,10 +196,10 @@ STATIC NTSTATUS IrpQueueQueryPendingPackets(_In_ PIRP Irp) { - PIRP_QUEUE_HEAD queue = GetIrpQueueHead(); + PIRP_QUEUE_HEAD queue = GetIrpQueueHead(); PDEFERRED_REPORT report = NULL; - NTSTATUS status = STATUS_UNSUCCESSFUL; - KIRQL irql = 0; + NTSTATUS status = STATUS_UNSUCCESSFUL; + KIRQL irql = 0; /* * Important we hold the lock before we call IsThereDeferredReport to @@ -242,7 +244,7 @@ VOID IrpQueueCompleteCancelledIrp(_In_ PIO_CSQ Csq, _In_ PIRP Irp) { UNREFERENCED_PARAMETER(Csq); - Irp->IoStatus.Status = STATUS_CANCELLED; + Irp->IoStatus.Status = STATUS_CANCELLED; Irp->IoStatus.Information = 0; ImpIofCompleteRequest(Irp, IO_NO_INCREMENT); } @@ -252,12 +254,14 @@ PDEFERRED_REPORT IrpQueueAllocateDeferredPacket(_In_ PVOID Buffer, _In_ UINT32 BufferSize) { PDEFERRED_REPORT report = ImpExAllocatePool2( - POOL_FLAG_NON_PAGED, sizeof(DEFERRED_REPORT), REPORT_POOL_TAG); + POOL_FLAG_NON_PAGED, + sizeof(DEFERRED_REPORT), + REPORT_POOL_TAG); if (!report) return NULL; - report->buffer = Buffer; + report->buffer = Buffer; report->buffer_size = BufferSize; return report; } @@ -266,9 +270,8 @@ IrpQueueAllocateDeferredPacket(_In_ PVOID Buffer, _In_ UINT32 BufferSize) STATIC VOID -IrpQueueDeferPacket(_In_ PIRP_QUEUE_HEAD Queue, - _In_ PVOID Buffer, - _In_ UINT32 BufferSize) +IrpQueueDeferPacket( + _In_ PIRP_QUEUE_HEAD Queue, _In_ PVOID Buffer, _In_ UINT32 BufferSize) { PDEFERRED_REPORT report = NULL; /* @@ -300,10 +303,10 @@ STATIC NTSTATUS IrpQueueCompletePacket(_In_ PVOID Buffer, _In_ ULONG BufferSize) { - NTSTATUS status = STATUS_UNSUCCESSFUL; - PIRP_QUEUE_HEAD queue = GetIrpQueueHead(); - PIRP irp = IoCsqRemoveNextIrp(&queue->csq, NULL); - UINT16 type = GetPacketType(Buffer); + NTSTATUS status = STATUS_UNSUCCESSFUL; + PIRP_QUEUE_HEAD queue = GetIrpQueueHead(); + PIRP irp = IoCsqRemoveNextIrp(&queue->csq, NULL); + UINT16 type = GetPacketType(Buffer); /* * If no irps are available in our queue, lets store it in a deferred @@ -323,7 +326,7 @@ IrpQueueCompletePacket(_In_ PVOID Buffer, _In_ ULONG BufferSize) */ if (!NT_SUCCESS(status)) { ImpExFreePoolWithTag(Buffer, REPORT_POOL_TAG); - irp->IoStatus.Status = STATUS_INSUFFICIENT_RESOURCES; + irp->IoStatus.Status = STATUS_INSUFFICIENT_RESOURCES; irp->IoStatus.Information = 0; ImpIofCompleteRequest(irp, IO_NO_INCREMENT); return status; @@ -331,7 +334,7 @@ IrpQueueCompletePacket(_In_ PVOID Buffer, _In_ ULONG BufferSize) IncrementPacketMetics(queue, type); - irp->IoStatus.Status = STATUS_SUCCESS; + irp->IoStatus.Status = STATUS_SUCCESS; irp->IoStatus.Information = BufferSize; IntCopyMemory(irp->AssociatedIrp.SystemBuffer, Buffer, BufferSize); ImpExFreePoolWithTag(Buffer, REPORT_POOL_TAG); @@ -357,9 +360,9 @@ STATIC VOID IrpQueueFreeDeferredPackets() { - PIRP_QUEUE_HEAD queue = GetIrpQueueHead(); + PIRP_QUEUE_HEAD queue = GetIrpQueueHead(); PDEFERRED_REPORT report = NULL; - KIRQL irql = 0; + KIRQL irql = 0; /* just in case... */ KeAcquireGuardedMutex(&queue->deferred_reports.lock); @@ -375,21 +378,22 @@ IrpQueueFreeDeferredPackets() NTSTATUS IrpQueueInitialise() { - NTSTATUS status = STATUS_UNSUCCESSFUL; - PIRP_QUEUE_HEAD queue = GetIrpQueueHead(); + NTSTATUS status = STATUS_UNSUCCESSFUL; + PIRP_QUEUE_HEAD queue = GetIrpQueueHead(); KeInitializeGuardedMutex(&queue->lock); KeInitializeGuardedMutex(&queue->deferred_reports.lock); InitializeListHead(&queue->queue); InitializeListHead(&queue->deferred_reports.head); - status = IoCsqInitialize(&queue->csq, - IrpQueueInsert, - IrpQueueRemove, - IrpQueuePeekNextEntry, - IrpQueueAcquireLock, - IrpQueueReleaseLock, - IrpQueueCompleteCancelledIrp); + status = IoCsqInitialize( + &queue->csq, + IrpQueueInsert, + IrpQueueRemove, + IrpQueuePeekNextEntry, + IrpQueueAcquireLock, + IrpQueueReleaseLock, + IrpQueueCompleteCancelledIrp); if (!NT_SUCCESS(status)) DEBUG_ERROR("IoCsqInitialize failed with status %x", status); @@ -398,17 +402,18 @@ IrpQueueInitialise() } VOID -SharedMappingWorkRoutine(_In_ PDEVICE_OBJECT DeviceObject, - _In_opt_ PVOID Context) +SharedMappingWorkRoutine( + _In_ PDEVICE_OBJECT DeviceObject, _In_opt_ PVOID Context) { - NTSTATUS status = STATUS_UNSUCCESSFUL; - HANDLE handle = NULL; - PSHARED_MAPPING state = (PSHARED_MAPPING)Context; + NTSTATUS status = STATUS_UNSUCCESSFUL; + HANDLE handle = NULL; + PSHARED_MAPPING state = (PSHARED_MAPPING)Context; InterlockedIncrement(&state->work_item_status); - DEBUG_VERBOSE("SharedMapping work routine called. OperationId: %lx", - state->kernel_buffer->operation_id); + DEBUG_VERBOSE( + "SharedMapping work routine called. OperationId: %lx", + state->kernel_buffer->operation_id); switch (state->kernel_buffer->operation_id) { case ssRunNmiCallbacks: @@ -427,13 +432,14 @@ SharedMappingWorkRoutine(_In_ PDEVICE_OBJECT DeviceObject, DEBUG_INFO( "SHARED_STATE_OPERATION_ID: ValidateDriverObjects Received."); - status = ImpPsCreateSystemThread(&handle, - PROCESS_ALL_ACCESS, - NULL, - NULL, - NULL, - HandleValidateDriversIOCTL, - NULL); + status = ImpPsCreateSystemThread( + &handle, + PROCESS_ALL_ACCESS, + NULL, + NULL, + NULL, + HandleValidateDriversIOCTL, + NULL); if (!NT_SUCCESS(status)) { DEBUG_ERROR("PsCreateSystemThread failed with status %x", status); @@ -473,8 +479,9 @@ SharedMappingWorkRoutine(_In_ PDEVICE_OBJECT DeviceObject, status = ValidateOurDriverImage(); if (!NT_SUCCESS(status)) - DEBUG_ERROR("VerifyInMemoryImageVsDiskImage failed with status %x", - status); + DEBUG_ERROR( + "VerifyInMemoryImageVsDiskImage failed with status %x", + status); break; @@ -494,8 +501,9 @@ SharedMappingWorkRoutine(_In_ PDEVICE_OBJECT DeviceObject, status = DetectEptHooksInKeyFunctions(); if (!NT_SUCCESS(status)) - DEBUG_ERROR("DetectEpthooksInKeyFunctions failed with status %x", - status); + DEBUG_ERROR( + "DetectEpthooksInKeyFunctions failed with status %x", + status); break; @@ -531,8 +539,9 @@ SharedMappingWorkRoutine(_In_ PDEVICE_OBJECT DeviceObject, status = ValidateWin32kDispatchTables(); if (!NT_SUCCESS(status)) - DEBUG_ERROR("ValidateWin32kDispatchTables failed with status %x", - status); + DEBUG_ERROR( + "ValidateWin32kDispatchTables failed with status %x", + status); break; @@ -545,10 +554,11 @@ end: /* again, we want to run our routine at apc level not dispatch level */ VOID -SharedMappingDpcRoutine(_In_ PKDPC Dpc, - _In_opt_ PVOID DeferredContext, - _In_opt_ PVOID SystemArgument1, - _In_opt_ PVOID SystemArgument2) +SharedMappingDpcRoutine( + _In_ PKDPC Dpc, + _In_opt_ PVOID DeferredContext, + _In_opt_ PVOID SystemArgument1, + _In_opt_ PVOID SystemArgument2) { PSHARED_MAPPING mapping = (PSHARED_MAPPING)DeferredContext; @@ -556,7 +566,10 @@ SharedMappingDpcRoutine(_In_ PKDPC Dpc, return; IoQueueWorkItem( - mapping->work_item, SharedMappingWorkRoutine, NormalWorkQueue, mapping); + mapping->work_item, + SharedMappingWorkRoutine, + NormalWorkQueue, + mapping); } #define REPEAT_TIME_15_SEC 30000 @@ -572,9 +585,9 @@ SharedMappingTerminate() while (mapping->work_item_status) YieldProcessor(); - mapping->active = FALSE; + mapping->active = FALSE; mapping->user_buffer = NULL; - mapping->size = 0; + mapping->size = 0; KeCancelTimer(&mapping->timer); IoFreeWorkItem(mapping->work_item); @@ -589,7 +602,7 @@ NTSTATUS SharedMappingInitialiseTimer(_In_ PSHARED_MAPPING Mapping) { LARGE_INTEGER due_time = {0}; - LONG period = 0; + LONG period = 0; due_time.QuadPart = -ABSOLUTE(SECONDS(30)); @@ -603,7 +616,10 @@ SharedMappingInitialiseTimer(_In_ PSHARED_MAPPING Mapping) KeInitializeDpc(&Mapping->timer_dpc, SharedMappingDpcRoutine, Mapping); KeInitializeTimer(&Mapping->timer); KeSetTimerEx( - &Mapping->timer, due_time, REPEAT_TIME_15_SEC, &Mapping->timer_dpc); + &Mapping->timer, + due_time, + REPEAT_TIME_15_SEC, + &Mapping->timer_dpc); DEBUG_VERBOSE("Initialised shared mapping event timer."); return STATUS_SUCCESS; @@ -611,16 +627,17 @@ SharedMappingInitialiseTimer(_In_ PSHARED_MAPPING Mapping) STATIC VOID -InitSharedMappingStructure(_Out_ PSHARED_MAPPING Mapping, - _In_ PVOID KernelBuffer, - _In_ PVOID UserBuffer, - _In_ PMDL Mdl) +InitSharedMappingStructure( + _Out_ PSHARED_MAPPING Mapping, + _In_ PVOID KernelBuffer, + _In_ PVOID UserBuffer, + _In_ PMDL Mdl) { - Mapping->kernel_buffer = (PSHARED_STATE)KernelBuffer; - Mapping->user_buffer = UserBuffer; - Mapping->mdl = Mdl; - Mapping->size = PAGE_SIZE; - Mapping->active = TRUE; + Mapping->kernel_buffer = (PSHARED_STATE)KernelBuffer; + Mapping->user_buffer = UserBuffer; + Mapping->mdl = Mdl; + Mapping->size = PAGE_SIZE; + Mapping->active = TRUE; Mapping->work_item_status = FALSE; } @@ -628,13 +645,13 @@ STATIC NTSTATUS SharedMappingInitialise(_In_ PIRP Irp) { - NTSTATUS status = STATUS_UNSUCCESSFUL; - PMDL mdl = NULL; - PSHARED_MAPPING mapping = NULL; + NTSTATUS status = STATUS_UNSUCCESSFUL; + PMDL mdl = NULL; + PSHARED_MAPPING mapping = NULL; PSHARED_MAPPING_INIT mapping_init = NULL; - PEPROCESS process = NULL; - PVOID buffer = NULL; - PVOID user_buffer = NULL; + PEPROCESS process = NULL; + PVOID buffer = NULL; + PVOID user_buffer = NULL; mapping = GetSharedMappingConfig(); @@ -667,18 +684,19 @@ SharedMappingInitialise(_In_ PIRP Irp) MmBuildMdlForNonPagedPool(mdl); __try { - user_buffer = MmMapLockedPagesSpecifyCache(mdl, - UserMode, - MmCached, - NULL, - FALSE, - NormalPagePriority | - MdlMappingNoExecute); + user_buffer = MmMapLockedPagesSpecifyCache( + mdl, + UserMode, + MmCached, + NULL, + FALSE, + NormalPagePriority | MdlMappingNoExecute); } __except (EXCEPTION_EXECUTE_HANDLER) { status = GetExceptionCode(); - DEBUG_ERROR("MmMapLockedPagesSpecifyCache failed with status %x", - status); + DEBUG_ERROR( + "MmMapLockedPagesSpecifyCache failed with status %x", + status); IoFreeMdl(mdl); ExFreePoolWithTag(buffer, POOL_TAG_INTEGRITY); return status; @@ -689,7 +707,7 @@ SharedMappingInitialise(_In_ PIRP Irp) mapping_init = (PSHARED_MAPPING_INIT)Irp->AssociatedIrp.SystemBuffer; mapping_init->buffer = user_buffer; - mapping_init->size = PAGE_SIZE; + mapping_init->size = PAGE_SIZE; return status; } @@ -707,14 +725,16 @@ DispatchApcOperation(_In_ PAPC_OPERATION_ID Operation) switch (Operation->operation_id) { case APC_OPERATION_STACKWALK: - DEBUG_INFO("Initiating APC stackwalk operation with operation id %i", - Operation->operation_id); + DEBUG_INFO( + "Initiating APC stackwalk operation with operation id %i", + Operation->operation_id); status = ValidateThreadsViaKernelApc(); if (!NT_SUCCESS(status)) - DEBUG_ERROR("ValidateThreadsViaKernelApc failed with status %x", - status); + DEBUG_ERROR( + "ValidateThreadsViaKernelApc failed with status %x", + status); return status; @@ -792,11 +812,11 @@ DeviceControl(_In_ PDEVICE_OBJECT DeviceObject, _Inout_ PIRP Irp) { PAGED_CODE(); - NTSTATUS status = STATUS_SUCCESS; + NTSTATUS status = STATUS_SUCCESS; PIO_STACK_LOCATION stack_location = IoGetCurrentIrpStackLocation(Irp); - HANDLE handle = NULL; - PKTHREAD thread = NULL; - BOOLEAN security_flag = FALSE; + HANDLE handle = NULL; + PKTHREAD thread = NULL; + BOOLEAN security_flag = FALSE; /* * LMAO @@ -835,13 +855,14 @@ DeviceControl(_In_ PDEVICE_OBJECT DeviceObject, _Inout_ PIRP Irp) * bug check under windows driver verifier. */ - status = ImpPsCreateSystemThread(&handle, - PROCESS_ALL_ACCESS, - NULL, - NULL, - NULL, - HandleValidateDriversIOCTL, - NULL); + status = ImpPsCreateSystemThread( + &handle, + PROCESS_ALL_ACCESS, + NULL, + NULL, + NULL, + HandleValidateDriversIOCTL, + NULL); if (!NT_SUCCESS(status)) { DEBUG_ERROR("PsCreateSystemThread failed with status %x", status); @@ -889,8 +910,9 @@ DeviceControl(_In_ PDEVICE_OBJECT DeviceObject, _Inout_ PIRP Irp) status = PerformVirtualizationDetection(Irp); if (!NT_SUCCESS(status)) - DEBUG_ERROR("PerformVirtualizationDetection failed with status %x", - status); + DEBUG_ERROR( + "PerformVirtualizationDetection failed with status %x", + status); break; @@ -908,30 +930,32 @@ DeviceControl(_In_ PDEVICE_OBJECT DeviceObject, _Inout_ PIRP Irp) DEBUG_VERBOSE("IOCTL_RETRIEVE_MODULE_EXECUTABLE_REGIONS Received"); - status = - ImpPsCreateSystemThread(&handle, - PROCESS_ALL_ACCESS, - NULL, - NULL, - NULL, - RetrieveInMemoryModuleExecutableSections, - Irp); + status = ImpPsCreateSystemThread( + &handle, + PROCESS_ALL_ACCESS, + NULL, + NULL, + NULL, + RetrieveInMemoryModuleExecutableSections, + Irp); if (!NT_SUCCESS(status)) { DEBUG_ERROR("PsCreateSystemThread failed with status %x", status); goto end; } - status = ImpObReferenceObjectByHandle(handle, - THREAD_ALL_ACCESS, - *PsThreadType, - KernelMode, - &thread, - NULL); + status = ImpObReferenceObjectByHandle( + handle, + THREAD_ALL_ACCESS, + *PsThreadType, + KernelMode, + &thread, + NULL); if (!NT_SUCCESS(status)) { - DEBUG_ERROR("ObReferenceObjectbyhandle failed with status %lx", - status); + DEBUG_ERROR( + "ObReferenceObjectbyhandle failed with status %lx", + status); ImpZwClose(handle); goto end; } @@ -982,8 +1006,9 @@ DeviceControl(_In_ PDEVICE_OBJECT DeviceObject, _Inout_ PIRP Irp) status = ValidateOurDriverImage(); if (!NT_SUCCESS(status)) - DEBUG_ERROR("VerifyInMemoryImageVsDiskImage failed with status %x", - status); + DEBUG_ERROR( + "VerifyInMemoryImageVsDiskImage failed with status %x", + status); break; @@ -1002,8 +1027,9 @@ DeviceControl(_In_ PDEVICE_OBJECT DeviceObject, _Inout_ PIRP Irp) status = ValidateProcessLoadedModule(Irp); if (!NT_SUCCESS(status)) - DEBUG_ERROR("ValidateProcessLoadedModule failed with status %x", - status); + DEBUG_ERROR( + "ValidateProcessLoadedModule failed with status %x", + status); break; @@ -1017,16 +1043,18 @@ DeviceControl(_In_ PDEVICE_OBJECT DeviceObject, _Inout_ PIRP Irp) status = ValidateIrpOutputBuffer(Irp, sizeof(SYSTEM_INFORMATION)); if (!NT_SUCCESS(status)) { - DEBUG_ERROR("ValidateIrpOutputBuffer failed with status %x", - status); + DEBUG_ERROR( + "ValidateIrpOutputBuffer failed with status %x", + status); goto end; } Irp->IoStatus.Information = sizeof(SYSTEM_INFORMATION); - IntCopyMemory(Irp->AssociatedIrp.SystemBuffer, - system_information, - sizeof(SYSTEM_INFORMATION)); + IntCopyMemory( + Irp->AssociatedIrp.SystemBuffer, + system_information, + sizeof(SYSTEM_INFORMATION)); break; @@ -1051,8 +1079,9 @@ DeviceControl(_In_ PDEVICE_OBJECT DeviceObject, _Inout_ PIRP Irp) status = DetectEptHooksInKeyFunctions(); if (!NT_SUCCESS(status)) - DEBUG_ERROR("DetectEpthooksInKeyFunctions failed with status %x", - status); + DEBUG_ERROR( + "DetectEpthooksInKeyFunctions failed with status %x", + status); break; @@ -1120,8 +1149,9 @@ DeviceControl(_In_ PDEVICE_OBJECT DeviceObject, _Inout_ PIRP Irp) status = SharedMappingInitialise(Irp); if (!NT_SUCCESS(status)) - DEBUG_ERROR("SharedMappingInitialise failed with status %x", - status); + DEBUG_ERROR( + "SharedMappingInitialise failed with status %x", + status); break; @@ -1129,13 +1159,14 @@ DeviceControl(_In_ PDEVICE_OBJECT DeviceObject, _Inout_ PIRP Irp) DEBUG_INFO("IOCTL_VALIDATE_PCI_DEVICES Received"); - status = ImpPsCreateSystemThread(&handle, - PROCESS_ALL_ACCESS, - NULL, - NULL, - NULL, - ValidatePciDevices, - NULL); + status = ImpPsCreateSystemThread( + &handle, + PROCESS_ALL_ACCESS, + NULL, + NULL, + NULL, + ValidatePciDevices, + NULL); if (!NT_SUCCESS(status)) { DEBUG_ERROR("PsCreateSystemThread failed with status %x", status); @@ -1152,14 +1183,16 @@ DeviceControl(_In_ PDEVICE_OBJECT DeviceObject, _Inout_ PIRP Irp) status = ValidateWin32kDispatchTables(); if (!NT_SUCCESS(status)) - DEBUG_ERROR("ValidateWin32kDispatchTables failed with status %x", - status); + DEBUG_ERROR( + "ValidateWin32kDispatchTables failed with status %x", + status); break; default: - DEBUG_WARNING("Invalid IOCTL passed to driver: %lx", - stack_location->Parameters.DeviceIoControl.IoControlCode); + DEBUG_WARNING( + "Invalid IOCTL passed to driver: %lx", + stack_location->Parameters.DeviceIoControl.IoControlCode); status = STATUS_INVALID_PARAMETER; break; diff --git a/driver/lib/stdlib.c b/driver/lib/stdlib.c index d0c1408..fda7756 100644 --- a/driver/lib/stdlib.c +++ b/driver/lib/stdlib.c @@ -4,7 +4,7 @@ VOID IntCopyMemory(_In_ PVOID Destination, _In_ PVOID Source, _In_ SIZE_T Length) { PUCHAR dest = (PUCHAR)Destination; - PUCHAR src = (PUCHAR)Source; + PUCHAR src = (PUCHAR)Source; for (SIZE_T index = 0; index < Length; index++) dest[index] = src[index]; diff --git a/driver/modules.c b/driver/modules.c index 6586b34..1311cb7 100644 --- a/driver/modules.c +++ b/driver/modules.c @@ -58,10 +58,10 @@ typedef struct _WHITELISTED_REGIONS { } WHITELISTED_REGIONS, *PWHITELISTED_REGIONS; typedef struct _NMI_CONTEXT { - UINT64 interrupted_rip; - UINT64 interrupted_rsp; - UINT64 kthread; - UINT32 callback_count; + UINT64 interrupted_rip; + UINT64 interrupted_rsp; + UINT64 kthread; + UINT32 callback_count; BOOLEAN user_thread; } NMI_CONTEXT, *PNMI_CONTEXT; @@ -72,8 +72,8 @@ typedef struct _NMI_CONTEXT { #define DPC_STACKWALK_FRAMES_TO_SKIP 3 typedef struct _DPC_CONTEXT { - UINT64 stack_frame[DPC_STACKWALK_STACKFRAME_COUNT]; - UINT16 frames_captured; + UINT64 stack_frame[DPC_STACKWALK_STACKFRAME_COUNT]; + UINT16 frames_captured; volatile BOOLEAN executed; } DPC_CONTEXT, *PDPC_CONTEXT; @@ -160,8 +160,8 @@ ValidateThreadViaKernelApcCallback( * are done using it. */ PRTL_MODULE_EXTENDED_INFO -FindSystemModuleByName(_In_ LPCSTR ModuleName, - _In_ PSYSTEM_MODULES SystemModules) +FindSystemModuleByName( + _In_ LPCSTR ModuleName, _In_ PSYSTEM_MODULES SystemModules) { PAGED_CODE(); @@ -182,26 +182,26 @@ FindSystemModuleByName(_In_ LPCSTR ModuleName, STATIC VOID -PopulateWhitelistedModuleBuffer(_Inout_ PWHITELISTED_REGIONS Whitelist, - _In_ PSYSTEM_MODULES SystemModules) +PopulateWhitelistedModuleBuffer( + _Inout_ PWHITELISTED_REGIONS Whitelist, _In_ PSYSTEM_MODULES SystemModules) { PAGED_CODE(); - LPCSTR entry = NULL; + LPCSTR entry = NULL; PRTL_MODULE_EXTENDED_INFO module = NULL; - PWHITELISTED_REGIONS region = NULL; + PWHITELISTED_REGIONS region = NULL; for (UINT32 index = 0; index < WHITELISTED_MODULE_COUNT; index++) { - entry = WHITELISTED_MODULES[index]; + entry = WHITELISTED_MODULES[index]; module = FindSystemModuleByName(entry, SystemModules); /* not everyone will contain all whitelisted modules */ if (!module) continue; - region = &Whitelist[index]; + region = &Whitelist[index]; region->base = (UINT64)module->ImageBase; - region->end = (UINT64)module->ImageBase + module->ImageSize; + region->end = (UINT64)module->ImageBase + module->ImageSize; } } @@ -214,16 +214,17 @@ GetDriverMajorDispatchFunction(_In_ PDRIVER_OBJECT Driver) STATIC BOOLEAN -DoesDriverHaveInvalidDispatchRoutine(_In_ PDRIVER_OBJECT Driver, - _In_ PSYSTEM_MODULES Modules, - _In_ PWHITELISTED_REGIONS Regions) +DoesDriverHaveInvalidDispatchRoutine( + _In_ PDRIVER_OBJECT Driver, + _In_ PSYSTEM_MODULES Modules, + _In_ PWHITELISTED_REGIONS Regions) { PAGED_CODE(); - UINT64 dispatch_function = 0; - UINT64 module_base = 0; - UINT64 module_end = 0; - PRTL_MODULE_EXTENDED_INFO module = NULL; + UINT64 dispatch_function = 0; + UINT64 module_base = 0; + UINT64 module_end = 0; + PRTL_MODULE_EXTENDED_INFO module = NULL; dispatch_function = GetDriverMajorDispatchFunction(Driver); @@ -242,7 +243,7 @@ DoesDriverHaveInvalidDispatchRoutine(_In_ PDRIVER_OBJECT Driver, return FALSE; module_base = (UINT64)module[index].ImageBase; - module_end = module_base + module[index].ImageSize; + module_end = module_base + module[index].ImageSize; /* firstly, check if its inside its own module */ if (dispatch_function >= module_base && dispatch_function <= module_end) @@ -270,8 +271,9 @@ DoesDriverHaveInvalidDispatchRoutine(_In_ PDRIVER_OBJECT Driver, return FALSE; } - DEBUG_WARNING("Driver with invalid dispatch routine found: %s", - module[index].FullPathName); + DEBUG_WARNING( + "Driver with invalid dispatch routine found: %s", + module[index].FullPathName); return TRUE; } @@ -281,13 +283,13 @@ DoesDriverHaveInvalidDispatchRoutine(_In_ PDRIVER_OBJECT Driver, STATIC BOOLEAN -DoesDriverObjectHaveBackingModule(_In_ PSYSTEM_MODULES ModuleInformation, - _In_ PDRIVER_OBJECT DriverObject) +DoesDriverObjectHaveBackingModule( + _In_ PSYSTEM_MODULES ModuleInformation, _In_ PDRIVER_OBJECT DriverObject) { PAGED_CODE(); PRTL_MODULE_EXTENDED_INFO modules = NULL; - PRTL_MODULE_EXTENDED_INFO entry = NULL; + PRTL_MODULE_EXTENDED_INFO entry = NULL; modules = (PRTL_MODULE_EXTENDED_INFO)ModuleInformation->address; @@ -302,8 +304,9 @@ DoesDriverObjectHaveBackingModule(_In_ PSYSTEM_MODULES ModuleInformation, } } - DEBUG_WARNING("Driver found with no backing system image at address: %llx", - (UINT64)DriverObject->DriverStart); + DEBUG_WARNING( + "Driver found with no backing system image at address: %llx", + (UINT64)DriverObject->DriverStart); return FALSE; } @@ -311,11 +314,10 @@ DoesDriverObjectHaveBackingModule(_In_ PSYSTEM_MODULES ModuleInformation, FORCEINLINE STATIC VOID -InitSystemModulesStructure(_Out_ PSYSTEM_MODULES Modules, - _In_ PVOID Buffer, - _In_ INT Count) +InitSystemModulesStructure( + _Out_ PSYSTEM_MODULES Modules, _In_ PVOID Buffer, _In_ INT Count) { - Modules->address = Buffer; + Modules->address = Buffer; Modules->module_count = Count; } @@ -325,16 +327,17 @@ GetSystemModuleInformation(_Out_ PSYSTEM_MODULES ModuleInformation) { PAGED_CODE(); - ULONG size = 0; - NTSTATUS status = STATUS_UNSUCCESSFUL; + ULONG size = 0; + NTSTATUS status = STATUS_UNSUCCESSFUL; PRTL_MODULE_EXTENDED_INFO buffer = NULL; if (!ModuleInformation) return STATUS_INVALID_PARAMETER; - status = RtlQueryModuleInformation(&size, - sizeof(RTL_MODULE_EXTENDED_INFO), - NULL); + status = RtlQueryModuleInformation( + &size, + sizeof(RTL_MODULE_EXTENDED_INFO), + NULL); if (!NT_SUCCESS(status)) { DEBUG_ERROR("RtlQueryModuleInformation failed with status %x", status); @@ -348,20 +351,23 @@ GetSystemModuleInformation(_Out_ PSYSTEM_MODULES ModuleInformation) return STATUS_MEMORY_NOT_ALLOCATED; } - status = RtlQueryModuleInformation(&size, - sizeof(RTL_MODULE_EXTENDED_INFO), - buffer); + status = RtlQueryModuleInformation( + &size, + sizeof(RTL_MODULE_EXTENDED_INFO), + buffer); if (!NT_SUCCESS(status)) { - DEBUG_ERROR("RtlQueryModuleInformation 2 failed with status %x", - status); + DEBUG_ERROR( + "RtlQueryModuleInformation 2 failed with status %x", + status); ExFreePoolWithTag(buffer, SYSTEM_MODULES_POOL); return STATUS_ABANDONED; } - InitSystemModulesStructure(ModuleInformation, - buffer, - ARRAYLEN(size, RTL_MODULE_EXTENDED_INFO)); + InitSystemModulesStructure( + ModuleInformation, + buffer, + ARRAYLEN(size, RTL_MODULE_EXTENDED_INFO)); return status; } @@ -370,9 +376,9 @@ STATIC VOID ReportInvalidDriverObject(_In_ PDRIVER_OBJECT Driver, _In_ UINT32 ReportSubType) { - UINT32 len = 0; - NTSTATUS status = STATUS_UNSUCCESSFUL; - ANSI_STRING string = {0}; + UINT32 len = 0; + NTSTATUS status = STATUS_UNSUCCESSFUL; + ANSI_STRING string = {0}; PMODULE_VALIDATION_FAILURE report = NULL; len = CryptRequestRequiredBufferLength(sizeof(MODULE_VALIDATION_FAILURE)); @@ -384,11 +390,11 @@ ReportInvalidDriverObject(_In_ PDRIVER_OBJECT Driver, _In_ UINT32 ReportSubType) INIT_REPORT_PACKET(report, REPORT_MODULE_VALIDATION_FAILURE, ReportSubType); report->driver_base_address = Driver->DriverStart; - report->driver_size = Driver->DriverSize; + report->driver_size = Driver->DriverSize; - string.Length = 0; + string.Length = 0; string.MaximumLength = MODULE_REPORT_DRIVER_NAME_BUFFER_SIZE; - string.Buffer = &report->driver_name; + string.Buffer = &report->driver_name; /* Continue regardless of result */ ImpRtlUnicodeStringToAnsiString(&string, &Driver->DriverName, FALSE); @@ -422,13 +428,14 @@ GetObjectFromDirectory(_In_ POBJECT_DIRECTORY_ENTRY Entry) STATIC VOID -ValidateDriverObjects(_In_ PSYSTEM_MODULES Modules, - _In_ POBJECT_DIRECTORY_ENTRY Entry, - _In_ PWHITELISTED_REGIONS Whitelist) +ValidateDriverObjects( + _In_ PSYSTEM_MODULES Modules, + _In_ POBJECT_DIRECTORY_ENTRY Entry, + _In_ PWHITELISTED_REGIONS Whitelist) { - NTSTATUS status = STATUS_UNSUCCESSFUL; - POBJECT_DIRECTORY_ENTRY entry = Entry; - PDRIVER_OBJECT driver = NULL; + NTSTATUS status = STATUS_UNSUCCESSFUL; + POBJECT_DIRECTORY_ENTRY entry = Entry; + PDRIVER_OBJECT driver = NULL; while (entry) { driver = GetObjectFromDirectory(entry); @@ -455,22 +462,23 @@ ValidateDriverObjectsWrapper(_In_ PSYSTEM_MODULES SystemModules) { PAGED_CODE(); - HANDLE handle = NULL; - OBJECT_ATTRIBUTES oa = {0}; - PVOID dir = {0}; - UNICODE_STRING dir_name = {0}; - PWHITELISTED_REGIONS wl = NULL; - NTSTATUS status = STATUS_UNSUCCESSFUL; - POBJECT_DIRECTORY dir_object = NULL; - POBJECT_DIRECTORY_ENTRY bucket = NULL; + HANDLE handle = NULL; + OBJECT_ATTRIBUTES oa = {0}; + PVOID dir = {0}; + UNICODE_STRING dir_name = {0}; + PWHITELISTED_REGIONS wl = NULL; + NTSTATUS status = STATUS_UNSUCCESSFUL; + POBJECT_DIRECTORY dir_object = NULL; + POBJECT_DIRECTORY_ENTRY bucket = NULL; ImpRtlInitUnicodeString(&dir_name, L"\\Driver"); - InitializeObjectAttributes(&oa, - &dir_name, - OBJ_CASE_INSENSITIVE, - NULL, - NULL); + InitializeObjectAttributes( + &oa, + &dir_name, + OBJ_CASE_INSENSITIVE, + NULL, + NULL); status = ImpZwOpenDirectoryObject(&handle, DIRECTORY_ALL_ACCESS, &oa); @@ -479,12 +487,13 @@ ValidateDriverObjectsWrapper(_In_ PSYSTEM_MODULES SystemModules) return status; } - status = ImpObReferenceObjectByHandle(handle, - DIRECTORY_ALL_ACCESS, - NULL, - KernelMode, - &dir, - NULL); + status = ImpObReferenceObjectByHandle( + handle, + DIRECTORY_ALL_ACCESS, + NULL, + KernelMode, + &dir, + NULL); if (!NT_SUCCESS(status)) { DEBUG_ERROR("ObReferenceObjectByHandle failed with status %x", status); @@ -520,8 +529,9 @@ ValidateDriverObjectsWrapper(_In_ PSYSTEM_MODULES SystemModules) PopulateWhitelistedModuleBuffer(wl, SystemModules); if (!NT_SUCCESS(status)) { - DEBUG_ERROR("PopulateWhitelistedModuleBuffer failed with status %x", - status); + DEBUG_ERROR( + "PopulateWhitelistedModuleBuffer failed with status %x", + status); goto end; } @@ -554,8 +564,8 @@ HandleValidateDriversIOCTL() { PAGED_CODE(); - NTSTATUS status = STATUS_UNSUCCESSFUL; - ULONG length = 0; + NTSTATUS status = STATUS_UNSUCCESSFUL; + ULONG length = 0; SYSTEM_MODULES modules = {0}; status = GetSystemModuleInformation(&modules); @@ -585,8 +595,8 @@ end: * boolean and remove the out variable. */ BOOLEAN -IsInstructionPointerInInvalidRegion(_In_ UINT64 Rip, - _In_ PSYSTEM_MODULES SystemModules) +IsInstructionPointerInInvalidRegion( + _In_ UINT64 Rip, _In_ PSYSTEM_MODULES SystemModules) { PAGED_CODE(); @@ -596,7 +606,7 @@ IsInstructionPointerInInvalidRegion(_In_ UINT64 Rip, /* Note that this does not check for HAL or PatchGuard Execution */ for (UINT32 index = 0; index < SystemModules->module_count; index++) { UINT64 base = (UINT64)modules[index].ImageBase; - UINT64 end = base + modules[index].ImageSize; + UINT64 end = base + modules[index].ImageSize; if (Rip >= base && Rip <= end) { return FALSE; @@ -607,11 +617,11 @@ IsInstructionPointerInInvalidRegion(_In_ UINT64 Rip, } BOOLEAN -IsInstructionPointerInsideSpecifiedModule(_In_ UINT64 Rip, - _In_ PRTL_MODULE_EXTENDED_INFO Module) +IsInstructionPointerInsideSpecifiedModule( + _In_ UINT64 Rip, _In_ PRTL_MODULE_EXTENDED_INFO Module) { UINT64 base = (UINT64)Module->ImageBase; - UINT64 end = base + Module->ImageSize; + UINT64 end = base + Module->ImageSize; if (Rip >= base && Rip <= end) return TRUE; @@ -623,11 +633,11 @@ STATIC VOID ReportNmiBlocking() { - NTSTATUS status = STATUS_UNSUCCESSFUL; - UINT32 len = 0; + NTSTATUS status = STATUS_UNSUCCESSFUL; + UINT32 len = 0; PNMI_CALLBACK_FAILURE report = NULL; - len = CryptRequestRequiredBufferLength(sizeof(NMI_CALLBACK_FAILURE)); + len = CryptRequestRequiredBufferLength(sizeof(NMI_CALLBACK_FAILURE)); report = ImpExAllocatePool2(POOL_FLAG_NON_PAGED, len, REPORT_POOL_TAG); if (!report) @@ -635,8 +645,8 @@ ReportNmiBlocking() INIT_REPORT_PACKET(report, REPORT_NMI_CALLBACK_FAILURE, 0); - report->kthread_address = NULL; - report->invalid_rip = NULL; + report->kthread_address = NULL; + report->invalid_rip = NULL; report->were_nmis_disabled = TRUE; status = CryptEncryptBuffer(report, len); @@ -654,8 +664,8 @@ STATIC VOID ReportMissingCidTableEntry(_In_ PNMI_CONTEXT Context) { - NTSTATUS status = STATUS_UNSUCCESSFUL; - UINT32 len = 0; + NTSTATUS status = STATUS_UNSUCCESSFUL; + UINT32 len = 0; PHIDDEN_SYSTEM_THREAD_REPORT report = NULL; len = CryptRequestRequiredBufferLength(sizeof(HIDDEN_SYSTEM_THREAD_REPORT)); @@ -668,8 +678,8 @@ ReportMissingCidTableEntry(_In_ PNMI_CONTEXT Context) report->found_in_kthreadlist = FALSE; // wip report->found_in_pspcidtable = FALSE; - report->thread_id = ImpPsGetThreadId(Context->kthread); - report->thread_address = Context->kthread; + report->thread_id = ImpPsGetThreadId(Context->kthread); + report->thread_address = Context->kthread; IntCopyMemory(report->thread, Context->kthread, sizeof(report->thread)); @@ -686,11 +696,11 @@ ReportMissingCidTableEntry(_In_ PNMI_CONTEXT Context) STATIC VOID -ReportInvalidRipFoundDuringNmi(_In_ PNMI_CONTEXT Context, - _In_ UINT32 ReportSubCode) +ReportInvalidRipFoundDuringNmi( + _In_ PNMI_CONTEXT Context, _In_ UINT32 ReportSubCode) { - NTSTATUS status = STATUS_UNSUCCESSFUL; - UINT32 len = 0; + NTSTATUS status = STATUS_UNSUCCESSFUL; + UINT32 len = 0; PNMI_CALLBACK_FAILURE report = NULL; len = CryptRequestRequiredBufferLength(sizeof(HIDDEN_SYSTEM_THREAD_REPORT)); @@ -701,8 +711,8 @@ ReportInvalidRipFoundDuringNmi(_In_ PNMI_CONTEXT Context, INIT_REPORT_PACKET(report, REPORT_NMI_CALLBACK_FAILURE, ReportSubCode); - report->kthread_address = Context->kthread; - report->invalid_rip = Context->interrupted_rip; + report->kthread_address = Context->kthread; + report->invalid_rip = Context->interrupted_rip; report->were_nmis_disabled = FALSE; status = CryptEncryptBuffer(report, len); @@ -764,8 +774,8 @@ AnalyseNmiData(_In_ PNMI_CONTEXT NmiContext, _In_ PSYSTEM_MODULES Modules) { PAGED_CODE(); - NTSTATUS status = STATUS_UNSUCCESSFUL; - BOOLEAN flag = FALSE; + NTSTATUS status = STATUS_UNSUCCESSFUL; + BOOLEAN flag = FALSE; PNMI_CONTEXT context = NULL; if (!NmiContext || !Modules) @@ -811,8 +821,9 @@ AnalyseNmiData(_In_ PNMI_CONTEXT NmiContext, _In_ PSYSTEM_MODULES Modules) if (!DoesThreadHaveValidCidEntry(context->kthread)) ReportMissingCidTableEntry(context); - if (IsInstructionPointerInInvalidRegion(context->interrupted_rip, - Modules)) + if (IsInstructionPointerInInvalidRegion( + context->interrupted_rip, + Modules)) ReportInvalidRipFoundDuringNmi(context, 0); if (context->user_thread) @@ -848,11 +859,11 @@ NmiCallback(_Inout_opt_ PVOID Context, _In_ BOOLEAN Handled) { UNREFERENCED_PARAMETER(Handled); - ULONG core = KeGetCurrentProcessorNumber(); - PNMI_CONTEXT context = &((PNMI_CONTEXT)Context)[core]; - UINT64 kpcr = 0; - TASK_STATE_SEGMENT_64* tss = NULL; - PMACHINE_FRAME machine_frame = NULL; + ULONG core = KeGetCurrentProcessorNumber(); + PNMI_CONTEXT context = &((PNMI_CONTEXT)Context)[core]; + UINT64 kpcr = 0; + TASK_STATE_SEGMENT_64* tss = NULL; + PMACHINE_FRAME machine_frame = NULL; if (!ARGUMENT_PRESENT(Context)) return TRUE; @@ -869,8 +880,8 @@ NmiCallback(_Inout_opt_ PVOID Context, _In_ BOOLEAN Handled) * safe to run at IRQL = HIGH_LEVEL, hence we need to manually unwind * the ISR stack to find the interrupted rip. */ - kpcr = __readmsr(IA32_GS_BASE); - tss = GetTaskStateSegment(kpcr); + kpcr = __readmsr(IA32_GS_BASE); + tss = GetTaskStateSegment(kpcr); machine_frame = GetIsrMachineFrame(tss); if (IsUserModeAddress(machine_frame->rip)) @@ -878,7 +889,7 @@ NmiCallback(_Inout_opt_ PVOID Context, _In_ BOOLEAN Handled) context->interrupted_rip = machine_frame->rip; context->interrupted_rsp = machine_frame->rsp; - context->kthread = PsGetCurrentThread(); + context->kthread = PsGetCurrentThread(); context->callback_count++; return TRUE; @@ -893,11 +904,12 @@ LaunchNonMaskableInterrupt() PAGED_CODE(); PKAFFINITY_EX affinity = NULL; - LARGE_INTEGER delay = {0}; + LARGE_INTEGER delay = {0}; - affinity = ImpExAllocatePool2(POOL_FLAG_NON_PAGED, - sizeof(KAFFINITY_EX), - PROC_AFFINITY_POOL); + affinity = ImpExAllocatePool2( + POOL_FLAG_NON_PAGED, + sizeof(KAFFINITY_EX), + PROC_AFFINITY_POOL); if (!affinity) return STATUS_MEMORY_NOT_ALLOCATED; @@ -927,11 +939,11 @@ HandleNmiIOCTL() { PAGED_CODE(); - NTSTATUS status = STATUS_UNSUCCESSFUL; - PVOID handle = NULL; + NTSTATUS status = STATUS_UNSUCCESSFUL; + PVOID handle = NULL; SYSTEM_MODULES modules = {0}; - PNMI_CONTEXT context = NULL; - UINT32 size = 0; + PNMI_CONTEXT context = NULL; + UINT32 size = 0; size = ImpKeQueryActiveProcessorCount(0) * sizeof(NMI_CONTEXT); @@ -1018,11 +1030,11 @@ STATIC VOID ReportApcStackwalkViolation(_In_ UINT64 Rip) { - NTSTATUS status = STATUS_UNSUCCESSFUL; - UINT32 len = 0; + NTSTATUS status = STATUS_UNSUCCESSFUL; + UINT32 len = 0; PAPC_STACKWALK_REPORT report = NULL; - len = CryptRequestRequiredBufferLength(sizeof(APC_STACKWALK_REPORT)); + len = CryptRequestRequiredBufferLength(sizeof(APC_STACKWALK_REPORT)); report = ImpExAllocatePool2(POOL_FLAG_NON_PAGED, len, REPORT_POOL_TAG); if (!report) @@ -1031,7 +1043,7 @@ ReportApcStackwalkViolation(_In_ UINT64 Rip) INIT_REPORT_PACKET(report, REPORT_APC_STACKWALK, 0); report->kthread_address = (UINT64)KeGetCurrentThread(); - report->invalid_rip = Rip; + report->invalid_rip = Rip; // report->driver ?? todo! status = CryptEncryptBuffer(report, len); @@ -1051,20 +1063,21 @@ ReportApcStackwalkViolation(_In_ UINT64 Rip) */ STATIC VOID -ApcKernelRoutine(_In_ PRKAPC Apc, - _Inout_ _Deref_pre_maybenull_ PKNORMAL_ROUTINE* NormalRoutine, - _Inout_ _Deref_pre_maybenull_ PVOID* NormalContext, - _Inout_ _Deref_pre_maybenull_ PVOID* SystemArgument1, - _Inout_ _Deref_pre_maybenull_ PVOID* SystemArgument2) +ApcKernelRoutine( + _In_ PRKAPC Apc, + _Inout_ _Deref_pre_maybenull_ PKNORMAL_ROUTINE* NormalRoutine, + _Inout_ _Deref_pre_maybenull_ PVOID* NormalContext, + _Inout_ _Deref_pre_maybenull_ PVOID* SystemArgument1, + _Inout_ _Deref_pre_maybenull_ PVOID* SystemArgument2) { PAGED_CODE(); - NTSTATUS status = STATUS_UNSUCCESSFUL; - PVOID buffer = NULL; - INT frames_captured = 0; - UINT64 frame = 0; - PAPC_STACKWALK_CONTEXT context = NULL; - PTHREAD_LIST_ENTRY entry = NULL; + NTSTATUS status = STATUS_UNSUCCESSFUL; + PVOID buffer = NULL; + INT frames_captured = 0; + UINT64 frame = 0; + PAPC_STACKWALK_CONTEXT context = NULL; + PTHREAD_LIST_ENTRY entry = NULL; context = (PAPC_STACKWALK_CONTEXT)Apc->NormalContext; @@ -1073,18 +1086,19 @@ ApcKernelRoutine(_In_ PRKAPC Apc, if (!entry) return; - buffer = ImpExAllocatePool2(POOL_FLAG_NON_PAGED, - STACK_FRAME_POOL_SIZE, - POOL_TAG_APC); + buffer = ImpExAllocatePool2( + POOL_FLAG_NON_PAGED, + STACK_FRAME_POOL_SIZE, + POOL_TAG_APC); if (!buffer) goto free; - frames_captured = - ImpRtlCaptureStackBackTrace(NULL, - STACK_FRAME_POOL_SIZE / sizeof(UINT64), - buffer, - NULL); + frames_captured = ImpRtlCaptureStackBackTrace( + NULL, + STACK_FRAME_POOL_SIZE / sizeof(UINT64), + buffer, + NULL); if (!frames_captured) goto free; @@ -1109,7 +1123,7 @@ free: FreeApcAndDecrementApcCount(Apc, APC_CONTEXT_ID_STACKWALK); - entry->apc = NULL; + entry->apc = NULL; entry->apc_queued = FALSE; } @@ -1118,9 +1132,10 @@ free: */ STATIC VOID -ApcNormalRoutine(_In_opt_ PVOID NormalContext, - _In_opt_ PVOID SystemArgument1, - _In_opt_ PVOID SystemArgument2) +ApcNormalRoutine( + _In_opt_ PVOID NormalContext, + _In_opt_ PVOID SystemArgument1, + _In_opt_ PVOID SystemArgument2) { PAGED_CODE(); } @@ -1131,18 +1146,18 @@ ApcNormalRoutine(_In_opt_ PVOID NormalContext, STATIC VOID -ValidateThreadViaKernelApcCallback(_In_ PTHREAD_LIST_ENTRY Entry, - _Inout_opt_ PVOID Context) +ValidateThreadViaKernelApcCallback( + _In_ PTHREAD_LIST_ENTRY Entry, _Inout_opt_ PVOID Context) { PAGED_CODE(); - PKAPC apc = NULL; - PLONG flags = NULL; - PCHAR prev_mode = NULL; - PUCHAR state = NULL; - BOOLEAN apc_queueable = FALSE; - LPCSTR proc_name = NULL; - PAPC_STACKWALK_CONTEXT context = NULL; + PKAPC apc = NULL; + PLONG flags = NULL; + PCHAR prev_mode = NULL; + PUCHAR state = NULL; + BOOLEAN apc_queueable = FALSE; + LPCSTR proc_name = NULL; + PAPC_STACKWALK_CONTEXT context = NULL; context = (PAPC_STACKWALK_CONTEXT)Context; @@ -1158,9 +1173,9 @@ ValidateThreadViaKernelApcCallback(_In_ PTHREAD_LIST_ENTRY Entry, * before before queueing ours. Since we filter out any system threads * this should be fine... c: */ - flags = RVA(PLONG, Entry->thread, KTHREAD_MISC_FLAGS_OFFSET); + flags = RVA(PLONG, Entry->thread, KTHREAD_MISC_FLAGS_OFFSET); prev_mode = RVA(PCHAR, Entry->thread, KTHREAD_PREVIOUS_MODE_OFFSET); - state = RVA(PUCHAR, Entry->thread, KTHREAD_STATE_OFFSET); + state = RVA(PUCHAR, Entry->thread, KTHREAD_STATE_OFFSET); /* * For now, lets only check for system threads. However, we also want to @@ -1186,14 +1201,15 @@ ValidateThreadViaKernelApcCallback(_In_ PTHREAD_LIST_ENTRY Entry, if (!apc) return; - ImpKeInitializeApc(apc, - Entry->thread, - OriginalApcEnvironment, - ApcKernelRoutine, - ApcRundownRoutine, - ApcNormalRoutine, - KernelMode, - Context); + ImpKeInitializeApc( + apc, + Entry->thread, + OriginalApcEnvironment, + ApcKernelRoutine, + ApcRundownRoutine, + ApcNormalRoutine, + KernelMode, + Context); if (!ImpKeInsertQueueApc(apc, NULL, NULL, IO_NO_INCREMENT)) { DEBUG_ERROR("KeInsertQueueApc failed with no status."); @@ -1201,7 +1217,7 @@ ValidateThreadViaKernelApcCallback(_In_ PTHREAD_LIST_ENTRY Entry, return; } - Entry->apc = apc; + Entry->apc = apc; Entry->apc_queued = TRUE; IncrementApcCount(APC_CONTEXT_ID_STACKWALK); @@ -1235,7 +1251,7 @@ ValidateThreadsViaKernelApc() { PAGED_CODE(); - NTSTATUS status = STATUS_UNSUCCESSFUL; + NTSTATUS status = STATUS_UNSUCCESSFUL; PAPC_STACKWALK_CONTEXT context = NULL; /* First, ensure we dont already have an ongoing operation */ @@ -1246,17 +1262,19 @@ ValidateThreadsViaKernelApc() return STATUS_SUCCESS; } - context = ImpExAllocatePool2(POOL_FLAG_NON_PAGED, - sizeof(APC_STACKWALK_CONTEXT), - POOL_TAG_APC); + context = ImpExAllocatePool2( + POOL_FLAG_NON_PAGED, + sizeof(APC_STACKWALK_CONTEXT), + POOL_TAG_APC); if (!context) return STATUS_MEMORY_NOT_ALLOCATED; context->header.context_id = APC_CONTEXT_ID_STACKWALK; - context->modules = ImpExAllocatePool2(POOL_FLAG_NON_PAGED, - sizeof(SYSTEM_MODULES), - POOL_TAG_APC); + context->modules = ImpExAllocatePool2( + POOL_FLAG_NON_PAGED, + sizeof(SYSTEM_MODULES), + POOL_TAG_APC); if (!context->modules) { ImpExFreePoolWithTag(context, POOL_TAG_APC); @@ -1290,10 +1308,11 @@ FreeApcStackwalkApcContextInformation(_Inout_ PAPC_STACKWALK_CONTEXT Context) } VOID -DpcStackwalkCallbackRoutine(_In_ PKDPC Dpc, - _In_opt_ PVOID DeferredContext, - _In_opt_ PVOID SystemArgument1, - _In_opt_ PVOID SystemArgument2) +DpcStackwalkCallbackRoutine( + _In_ PKDPC Dpc, + _In_opt_ PVOID DeferredContext, + _In_opt_ PVOID SystemArgument1, + _In_opt_ PVOID SystemArgument2) { UNREFERENCED_PARAMETER(Dpc); UNREFERENCED_PARAMETER(SystemArgument2); @@ -1305,11 +1324,11 @@ DpcStackwalkCallbackRoutine(_In_ PKDPC Dpc, context = &((PDPC_CONTEXT)DeferredContext)[KeGetCurrentProcessorNumber()]; - context->frames_captured = - ImpRtlCaptureStackBackTrace(DPC_STACKWALK_FRAMES_TO_SKIP, - DPC_STACKWALK_STACKFRAME_COUNT, - &context->stack_frame, - NULL); + context->frames_captured = ImpRtlCaptureStackBackTrace( + DPC_STACKWALK_FRAMES_TO_SKIP, + DPC_STACKWALK_STACKFRAME_COUNT, + &context->stack_frame, + NULL); InterlockedExchange(&context->executed, TRUE); @@ -1318,22 +1337,22 @@ DpcStackwalkCallbackRoutine(_In_ PKDPC Dpc, ImpKeSignalCallDpcDone(SystemArgument1); #pragma warning(pop) - DEBUG_VERBOSE("Executed DPC on core: %lx, with %lx frames captured.", - KeGetCurrentProcessorNumber(), - context->frames_captured); + DEBUG_VERBOSE( + "Executed DPC on core: %lx, with %lx frames captured.", + KeGetCurrentProcessorNumber(), + context->frames_captured); } STATIC VOID -ReportDpcStackwalkViolation(_In_ PDPC_CONTEXT Context, - _In_ UINT64 Frame, - _In_ UINT32 ReportSubtype) +ReportDpcStackwalkViolation( + _In_ PDPC_CONTEXT Context, _In_ UINT64 Frame, _In_ UINT32 ReportSubtype) { - NTSTATUS status = STATUS_UNSUCCESSFUL; - UINT32 len = 0; + NTSTATUS status = STATUS_UNSUCCESSFUL; + UINT32 len = 0; PDPC_STACKWALK_REPORT report = NULL; - len = CryptRequestRequiredBufferLength(sizeof(DPC_STACKWALK_REPORT)); + len = CryptRequestRequiredBufferLength(sizeof(DPC_STACKWALK_REPORT)); report = ImpExAllocatePool2(POOL_FLAG_NON_PAGED, len, REPORT_POOL_TAG); if (!report) @@ -1342,7 +1361,7 @@ ReportDpcStackwalkViolation(_In_ PDPC_CONTEXT Context, INIT_REPORT_PACKET(report, REPORT_DPC_STACKWALK, ReportSubtype); report->kthread_address = PsGetCurrentThread(); - report->invalid_rip = Frame; + report->invalid_rip = Frame; // IntCopyMemory(report->driver, // (UINT64)Context[core].stack_frame[frame] @@ -1365,14 +1384,15 @@ VOID ValidateDpcStackFrame(_In_ PDPC_CONTEXT Context, _In_ PSYSTEM_MODULES Modules) { NTSTATUS status = STATUS_UNSUCCESSFUL; - BOOLEAN flag = FALSE; - UINT64 rip = 0; + BOOLEAN flag = FALSE; + UINT64 rip = 0; /* With regards to this, lets only check the interrupted rip */ if (DoesRetInstructionCauseException(Context->stack_frame[0])) - ReportDpcStackwalkViolation(Context, - Context->stack_frame[0], - REPORT_SUBTYPE_EXCEPTION_THROWING_RET); + ReportDpcStackwalkViolation( + Context, + Context->stack_frame[0], + REPORT_SUBTYPE_EXCEPTION_THROWING_RET); for (UINT32 frame = 0; frame < Context->frames_captured; frame++) { rip = Context->stack_frame[frame]; @@ -1384,19 +1404,20 @@ ValidateDpcStackFrame(_In_ PDPC_CONTEXT Context, _In_ PSYSTEM_MODULES Modules) STATIC VOID -ValidateDpcCapturedStack(_In_ PSYSTEM_MODULES Modules, - _In_ PDPC_CONTEXT Context) +ValidateDpcCapturedStack( + _In_ PSYSTEM_MODULES Modules, _In_ PDPC_CONTEXT Context) { - BOOLEAN flag = FALSE; + BOOLEAN flag = FALSE; PDPC_CONTEXT context = NULL; - UINT32 count = ImpKeQueryActiveProcessorCount(0); + UINT32 count = ImpKeQueryActiveProcessorCount(0); for (UINT32 core = 0; core < count; core++) { context = &Context[core]; if (!context->executed) - DEBUG_WARNING("DPC Stackwalk routine not executed. Core: %lx", - core); + DEBUG_WARNING( + "DPC Stackwalk routine not executed. Core: %lx", + core); ValidateDpcStackFrame(&Context[core], Modules); } @@ -1412,12 +1433,12 @@ ValidateDpcCapturedStack(_In_ PSYSTEM_MODULES Modules, NTSTATUS DispatchStackwalkToEachCpuViaDpc() { - NTSTATUS status = STATUS_UNSUCCESSFUL; - PDPC_CONTEXT context = NULL; + NTSTATUS status = STATUS_UNSUCCESSFUL; + PDPC_CONTEXT context = NULL; SYSTEM_MODULES modules = {0}; - UINT32 size = 0; + UINT32 size = 0; - size = ImpKeQueryActiveProcessorCount(0) * sizeof(DPC_CONTEXT); + size = ImpKeQueryActiveProcessorCount(0) * sizeof(DPC_CONTEXT); context = ImpExAllocatePool2(POOL_FLAG_NON_PAGED, size, POOL_TAG_DPC); if (!context) @@ -1453,10 +1474,11 @@ end: /* todo: walk the chain of pointers to prevent jmp chaining */ STATIC VOID -ValidateTableDispatchRoutines(_In_ PVOID* Base, - _In_ UINT32 Entries, - _In_ PSYSTEM_MODULES Modules, - _Out_ PVOID* Routine) +ValidateTableDispatchRoutines( + _In_ PVOID* Base, + _In_ UINT32 Entries, + _In_ PSYSTEM_MODULES Modules, + _Out_ PVOID* Routine) { for (UINT32 index = 0; index < Entries; index++) { if (!Base[index]) @@ -1490,15 +1512,15 @@ GetHalPrivateDispatchTableRoutineCount(_In_ PRTL_OSVERSIONINFOW VersionInfo) STATIC NTSTATUS -ValidateHalPrivateDispatchTable(_Out_ PVOID* Routine, - _In_ PSYSTEM_MODULES Modules) +ValidateHalPrivateDispatchTable( + _Out_ PVOID* Routine, _In_ PSYSTEM_MODULES Modules) { - NTSTATUS status = STATUS_UNSUCCESSFUL; - PVOID table = NULL; - UNICODE_STRING string = RTL_CONSTANT_STRING(L"HalPrivateDispatchTable"); - PVOID* base = NULL; + NTSTATUS status = STATUS_UNSUCCESSFUL; + PVOID table = NULL; + UNICODE_STRING string = RTL_CONSTANT_STRING(L"HalPrivateDispatchTable"); + PVOID* base = NULL; RTL_OSVERSIONINFOW os_info = {0}; - UINT32 count = 0; + UINT32 count = 0; DEBUG_VERBOSE("Validating HalPrivateDispatchTable."); @@ -1514,7 +1536,7 @@ ValidateHalPrivateDispatchTable(_Out_ PVOID* Routine, return status; } - base = (UINT64)table + sizeof(UINT64); + base = (UINT64)table + sizeof(UINT64); count = GetHalPrivateDispatchTableRoutineCount(&os_info); ValidateTableDispatchRoutines(base, count, Modules, Routine); @@ -1537,8 +1559,9 @@ ValidateHalDispatchTable(_Out_ PVOID* Routine, _In_ PSYSTEM_MODULES Modules) * What if there are 2 invalid routines? hmm.. tink. */ - if (IsInstructionPointerInInvalidRegion(HalQuerySystemInformation, - Modules)) { + if (IsInstructionPointerInInvalidRegion( + HalQuerySystemInformation, + Modules)) { *Routine = HalQuerySystemInformation; goto end; } @@ -1553,8 +1576,9 @@ ValidateHalDispatchTable(_Out_ PVOID* Routine, _In_ PSYSTEM_MODULES Modules) goto end; } - if (IsInstructionPointerInInvalidRegion(HalReferenceHandlerForBus, - Modules)) { + if (IsInstructionPointerInInvalidRegion( + HalReferenceHandlerForBus, + Modules)) { *Routine = HalReferenceHandlerForBus; goto end; } @@ -1564,8 +1588,9 @@ ValidateHalDispatchTable(_Out_ PVOID* Routine, _In_ PSYSTEM_MODULES Modules) goto end; } - if (IsInstructionPointerInInvalidRegion(HalDereferenceBusHandler, - Modules)) { + if (IsInstructionPointerInInvalidRegion( + HalDereferenceBusHandler, + Modules)) { *Routine = HalDereferenceBusHandler; goto end; } @@ -1585,8 +1610,9 @@ ValidateHalDispatchTable(_Out_ PVOID* Routine, _In_ PSYSTEM_MODULES Modules) goto end; } - if (IsInstructionPointerInInvalidRegion(HalGetInterruptTranslator, - Modules)) { + if (IsInstructionPointerInInvalidRegion( + HalGetInterruptTranslator, + Modules)) { *Routine = HalGetInterruptTranslator; goto end; } @@ -1621,8 +1647,9 @@ ValidateHalDispatchTable(_Out_ PVOID* Routine, _In_ PSYSTEM_MODULES Modules) goto end; } - if (IsInstructionPointerInInvalidRegion(HalSetPciErrorHandlerCallback, - Modules)) { + if (IsInstructionPointerInInvalidRegion( + HalSetPciErrorHandlerCallback, + Modules)) { *Routine = HalSetPciErrorHandlerCallback; goto end; } @@ -1640,8 +1667,8 @@ STATIC VOID ReportDataTableInvalidRoutine(_In_ TABLE_ID TableId, _In_ UINT64 Address) { - NTSTATUS status = STATUS_UNSUCCESSFUL; - UINT32 len = 0; + NTSTATUS status = STATUS_UNSUCCESSFUL; + UINT32 len = 0; PDATA_TABLE_ROUTINE_REPORT report = NULL; len = CryptRequestRequiredBufferLength(sizeof(DATA_TABLE_ROUTINE_REPORT)); @@ -1650,15 +1677,16 @@ ReportDataTableInvalidRoutine(_In_ TABLE_ID TableId, _In_ UINT64 Address) if (!report) return; - DEBUG_WARNING("Invalid data table routine found. Table: %lx, Address: %llx", - TableId, - Address); + DEBUG_WARNING( + "Invalid data table routine found. Table: %lx, Address: %llx", + TableId, + Address); INIT_REPORT_PACKET(report, REPORT_DATA_TABLE_ROUTINE, 0); - report->address = Address; + report->address = Address; report->table_id = TableId; - report->index = 0; + report->index = 0; IntCopyMemory(report->routine, Address, DATA_TABLE_ROUTINE_BUF_SIZE); @@ -1676,10 +1704,10 @@ ReportDataTableInvalidRoutine(_In_ TABLE_ID TableId, _In_ UINT64 Address) NTSTATUS ValidateHalDispatchTables() { - NTSTATUS status = STATUS_UNSUCCESSFUL; - SYSTEM_MODULES modules = {0}; - PVOID routine1 = NULL; - PVOID routine2 = NULL; + NTSTATUS status = STATUS_UNSUCCESSFUL; + SYSTEM_MODULES modules = {0}; + PVOID routine1 = NULL; + PVOID routine2 = NULL; status = GetSystemModuleInformation(&modules); @@ -1698,8 +1726,9 @@ ValidateHalDispatchTables() status = ValidateHalPrivateDispatchTable(&routine2, &modules); if (!NT_SUCCESS(status)) { - DEBUG_ERROR("ValidateHalPrivateDispatchTable failed with status %x", - status); + DEBUG_ERROR( + "ValidateHalPrivateDispatchTable failed with status %x", + status); goto end; } @@ -1716,28 +1745,29 @@ end: } NTSTATUS -GetDriverObjectByDriverName(_In_ PUNICODE_STRING DriverName, - _Out_ PDRIVER_OBJECT* DriverObject) +GetDriverObjectByDriverName( + _In_ PUNICODE_STRING DriverName, _Out_ PDRIVER_OBJECT* DriverObject) { - HANDLE handle = NULL; - OBJECT_ATTRIBUTES attributes = {0}; - PVOID dir = {0}; - UNICODE_STRING dir_name = {0}; - NTSTATUS status = STATUS_UNSUCCESSFUL; - POBJECT_DIRECTORY dir_object = NULL; - POBJECT_DIRECTORY_ENTRY entry = NULL; - POBJECT_DIRECTORY_ENTRY sub_entry = NULL; - PDRIVER_OBJECT driver = NULL; + HANDLE handle = NULL; + OBJECT_ATTRIBUTES attributes = {0}; + PVOID dir = {0}; + UNICODE_STRING dir_name = {0}; + NTSTATUS status = STATUS_UNSUCCESSFUL; + POBJECT_DIRECTORY dir_object = NULL; + POBJECT_DIRECTORY_ENTRY entry = NULL; + POBJECT_DIRECTORY_ENTRY sub_entry = NULL; + PDRIVER_OBJECT driver = NULL; *DriverObject = NULL; ImpRtlInitUnicodeString(&dir_name, L"\\Driver"); - InitializeObjectAttributes(&attributes, - &dir_name, - OBJ_CASE_INSENSITIVE, - NULL, - NULL); + InitializeObjectAttributes( + &attributes, + &dir_name, + OBJ_CASE_INSENSITIVE, + NULL, + NULL); status = ImpZwOpenDirectoryObject(&handle, DIRECTORY_ALL_ACCESS, &attributes); @@ -1747,12 +1777,13 @@ GetDriverObjectByDriverName(_In_ PUNICODE_STRING DriverName, return status; } - status = ImpObReferenceObjectByHandle(handle, - DIRECTORY_ALL_ACCESS, - NULL, - KernelMode, - &dir, - NULL); + status = ImpObReferenceObjectByHandle( + handle, + DIRECTORY_ALL_ACCESS, + NULL, + KernelMode, + &dir, + NULL); if (!NT_SUCCESS(status)) { DEBUG_ERROR("ObReferenceObjectByHandle failed with status %x", status); @@ -1775,9 +1806,10 @@ GetDriverObjectByDriverName(_In_ PUNICODE_STRING DriverName, while (sub_entry) { driver = GetObjectFromDirectory(sub_entry); - if (!RtlCompareUnicodeString(DriverName, - &driver->DriverName, - FALSE)) { + if (!RtlCompareUnicodeString( + DriverName, + &driver->DriverName, + FALSE)) { *DriverObject = driver; goto end; } @@ -1862,11 +1894,11 @@ PVOID FindChainedPointerEnding(_In_ PVOID* Start) { PVOID* current = *Start; - PVOID prev = Start; + PVOID prev = Start; while (IsValidKernelAddress(current)) { __try { - prev = current; + prev = current; current = *current; } __except (EXCEPTION_EXECUTE_HANDLER) { @@ -1985,11 +2017,11 @@ FindChainedPointerEnding(_In_ PVOID* Start) STATIC VOID -ReportWin32kBase_DxgInterfaceViolation(_In_ UINT32 TableIndex, - _In_ UINT64 Address) +ReportWin32kBase_DxgInterfaceViolation( + _In_ UINT32 TableIndex, _In_ UINT64 Address) { - NTSTATUS status = STATUS_UNSUCCESSFUL; - UINT32 len = 0; + NTSTATUS status = STATUS_UNSUCCESSFUL; + UINT32 len = 0; PDATA_TABLE_ROUTINE_REPORT report = NULL; len = CryptRequestRequiredBufferLength(sizeof(DATA_TABLE_ROUTINE_REPORT)); @@ -2000,9 +2032,9 @@ ReportWin32kBase_DxgInterfaceViolation(_In_ UINT32 TableIndex, INIT_REPORT_PACKET(report, REPORT_DATA_TABLE_ROUTINE, 0); - report->address = Address; + report->address = Address; report->table_id = Win32kBase_gDxgInterface; - report->index = TableIndex; + report->index = TableIndex; // todo! report->routine = ?? // todo: maybe get routine by name from index ? @@ -2021,14 +2053,14 @@ STATIC NTSTATUS ValidateWin32kBase_gDxgInterface() { - NTSTATUS status = STATUS_UNSUCCESSFUL; - SYSTEM_MODULES modules = {0}; - PRTL_MODULE_EXTENDED_INFO win32kbase = NULL; - PRTL_MODULE_EXTENDED_INFO dxgkrnl = NULL; - KAPC_STATE apc = {0}; - PKPROCESS winlogon = NULL; - PVOID* dxg_interface = NULL; - PVOID entry = NULL; + NTSTATUS status = STATUS_UNSUCCESSFUL; + SYSTEM_MODULES modules = {0}; + PRTL_MODULE_EXTENDED_INFO win32kbase = NULL; + PRTL_MODULE_EXTENDED_INFO dxgkrnl = NULL; + KAPC_STATE apc = {0}; + PKPROCESS winlogon = NULL; + PVOID* dxg_interface = NULL; + PVOID entry = NULL; status = GetSystemModuleInformation(&modules); diff --git a/driver/pe.c b/driver/pe.c index 6dfb9c0..4b72a0e 100644 --- a/driver/pe.c +++ b/driver/pe.c @@ -55,19 +55,21 @@ PeGetExportDataDirectorySafe(_In_ PVOID Image) } PIMAGE_EXPORT_DIRECTORY -PeGetExportDirectory(_In_ PVOID Image, - _In_ PIMAGE_DATA_DIRECTORY ExportDataDirectory) +PeGetExportDirectory( + _In_ PVOID Image, _In_ PIMAGE_DATA_DIRECTORY ExportDataDirectory) { if (!ExportDataDirectory->VirtualAddress || !ExportDataDirectory->Size) return NULL; return RVA( - PIMAGE_EXPORT_DIRECTORY, Image, ExportDataDirectory->VirtualAddress); + PIMAGE_EXPORT_DIRECTORY, + Image, + ExportDataDirectory->VirtualAddress); } PIMAGE_EXPORT_DIRECTORY -PeGetExportDirectorySafe(_In_ PVOID Image, - _In_ PIMAGE_DATA_DIRECTORY ExportDataDirectory) +PeGetExportDirectorySafe( + _In_ PVOID Image, _In_ PIMAGE_DATA_DIRECTORY ExportDataDirectory) { if (!MmIsAddressValid(Image)) return NULL; @@ -76,7 +78,9 @@ PeGetExportDirectorySafe(_In_ PVOID Image, return NULL; return RVA( - PIMAGE_EXPORT_DIRECTORY, Image, ExportDataDirectory->VirtualAddress); + PIMAGE_EXPORT_DIRECTORY, + Image, + ExportDataDirectory->VirtualAddress); } UINT32 @@ -97,9 +101,9 @@ GetSectionCountSafe(_In_ PNT_HEADER_64 Header) PVOID PeFindExportByName(_In_ PVOID Image, _In_ PCHAR Name) { - ANSI_STRING target = {0}; - PNT_HEADER_64 nt = NULL; - PIMAGE_DATA_DIRECTORY data = NULL; + ANSI_STRING target = {0}; + PNT_HEADER_64 nt = NULL; + PIMAGE_DATA_DIRECTORY data = NULL; PIMAGE_EXPORT_DIRECTORY export = NULL; RtlInitAnsiString(&target, Name); @@ -119,18 +123,14 @@ PeFindExportByName(_In_ PVOID Image, _In_ PCHAR Name) if (!export) return NULL; - PUINT32 functions = - RVA(PUINT32, Image, export->AddressOfFunctions); - PUINT32 names = - RVA(PUINT32, Image, export->AddressOfNames); - PUINT16 ordinals = - RVA(PUINT16, Image, export->AddressOfNameOrdinals); + PUINT32 functions = RVA(PUINT32, Image, export->AddressOfFunctions); + PUINT32 names = RVA(PUINT32, Image, export->AddressOfNames); + PUINT16 ordinals = RVA(PUINT16, Image, export->AddressOfNameOrdinals); for (UINT32 index = 0; index < export->NumberOfNames; index++) { PCHAR export = RVA(PCHAR, Image, names[index]); if (!IntCompareString(Name, export)) - return RVA( - PVOID, Image, functions[ordinals[index]]); + return RVA(PVOID, Image, functions[ordinals[index]]); } return NULL; diff --git a/driver/pool.c b/driver/pool.c index f411682..f47004e 100644 --- a/driver/pool.c +++ b/driver/pool.c @@ -4,9 +4,9 @@ #include "callbacks.h" +#include "crypt.h" #include "ia32.h" #include "imports.h" -#include "crypt.h" #include "lib/stdlib.h" @@ -56,28 +56,30 @@ typedef struct _PROCESS_SCAN_CONTEXT { STATIC BOOLEAN -ValidateIfAddressIsProcessStructure(_In_ PVOID Address, - _In_ PPOOL_HEADER PoolHeader); +ValidateIfAddressIsProcessStructure( + _In_ PVOID Address, _In_ PPOOL_HEADER PoolHeader); STATIC VOID -ScanPageForKernelObjectAllocation(_In_ UINT64 PageBase, - _In_ ULONG PageSize, - _In_ ULONG ObjectIndex, - _Inout_ PPROCESS_SCAN_CONTEXT Context); +ScanPageForKernelObjectAllocation( + _In_ UINT64 PageBase, + _In_ ULONG PageSize, + _In_ ULONG ObjectIndex, + _Inout_ PPROCESS_SCAN_CONTEXT Context); STATIC BOOLEAN -IsPhysicalAddressInPhysicalMemoryRange(_In_ UINT64 PhysicalAddress, - _In_ PPHYSICAL_MEMORY_RANGE - PhysicalMemoryRanges); +IsPhysicalAddressInPhysicalMemoryRange( + _In_ UINT64 PhysicalAddress, + _In_ PPHYSICAL_MEMORY_RANGE PhysicalMemoryRanges); STATIC VOID -EnumerateKernelLargePages(_In_ UINT64 PageBase, - _In_ ULONG PageSize, - _In_ PPROCESS_SCAN_CONTEXT Context, - _In_ ULONG ObjectIndex); +EnumerateKernelLargePages( + _In_ UINT64 PageBase, + _In_ ULONG PageSize, + _In_ PPROCESS_SCAN_CONTEXT Context, + _In_ ULONG ObjectIndex); STATIC VOID @@ -89,8 +91,8 @@ IncrementProcessCounter(_In_ PPROCESS_LIST_ENTRY Node, _In_opt_ PVOID Context); STATIC VOID -CheckIfProcessAllocationIsInProcessList(_In_ PPROCESS_LIST_ENTRY Node, - _In_opt_ PVOID Context); +CheckIfProcessAllocationIsInProcessList( + _In_ PPROCESS_LIST_ENTRY Node, _In_opt_ PVOID Context); #ifdef ALLOC_PRAGMA # pragma alloc_text(PAGE, GetGlobalDebuggerData) @@ -105,9 +107,9 @@ GetGlobalDebuggerData() { PAGED_CODE(); - CONTEXT context = {0}; - PDUMP_HEADER dump_header = {0}; - UINT64 thread_state = 0; + CONTEXT context = {0}; + PDUMP_HEADER dump_header = {0}; + UINT64 thread_state = 0; PKDDEBUGGER_DATA64 debugger_data = NULL; context.ContextFlags = CONTEXT_FULL; @@ -115,23 +117,35 @@ GetGlobalDebuggerData() RtlCaptureContext(&context); dump_header = ImpExAllocatePool2( - POOL_FLAG_NON_PAGED, DUMP_BLOCK_SIZE, POOL_DUMP_BLOCK_TAG); + POOL_FLAG_NON_PAGED, + DUMP_BLOCK_SIZE, + POOL_DUMP_BLOCK_TAG); if (!dump_header) goto end; KeCapturePersistentThreadState( - &context, NULL, NULL, NULL, NULL, NULL, NULL, dump_header); + &context, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + dump_header); debugger_data = (PKDDEBUGGER_DATA64)ExAllocatePool2( - POOL_FLAG_NON_PAGED, sizeof(KDDEBUGGER_DATA64), POOL_DEBUGGER_DATA_TAG); + POOL_FLAG_NON_PAGED, + sizeof(KDDEBUGGER_DATA64), + POOL_DEBUGGER_DATA_TAG); if (!debugger_data) goto end; - IntCopyMemory(debugger_data, - dump_header->KdDebuggerDataBlock, - sizeof(KDDEBUGGER_DATA64)); + IntCopyMemory( + debugger_data, + dump_header->KdDebuggerDataBlock, + sizeof(KDDEBUGGER_DATA64)); end: @@ -200,25 +214,25 @@ GetPsActiveProcessHead(_Out_ PUINT64 Address) */ STATIC BOOLEAN -ValidateIfAddressIsProcessStructure(_In_ PVOID Address, - _In_ PPOOL_HEADER PoolHeader) +ValidateIfAddressIsProcessStructure( + _In_ PVOID Address, _In_ PPOOL_HEADER PoolHeader) { - UINT64 peak_virtual_size = 0; - UINT64 dir_table_base = 0; - UINT64 allocation_size = 0; - UINT64 peb = 0; - UINT64 object_table = 0; - BOOLEAN peb_test = FALSE; - BOOLEAN object_table_test = FALSE; - UINT64 allocation_size_test = 0; + UINT64 peak_virtual_size = 0; + UINT64 dir_table_base = 0; + UINT64 allocation_size = 0; + UINT64 peb = 0; + UINT64 object_table = 0; + BOOLEAN peb_test = FALSE; + BOOLEAN object_table_test = FALSE; + UINT64 allocation_size_test = 0; - if (ImpMmIsAddressValid((UINT64)Address + - KPROCESS_DIRECTORY_TABLE_BASE_OFFSET)) + if (ImpMmIsAddressValid( + (UINT64)Address + KPROCESS_DIRECTORY_TABLE_BASE_OFFSET)) dir_table_base = *(UINT64*)((UINT64)Address + KPROCESS_DIRECTORY_TABLE_BASE_OFFSET); - if (ImpMmIsAddressValid((UINT64)Address + - EPROCESS_PEAK_VIRTUAL_SIZE_OFFSET)) + if (ImpMmIsAddressValid( + (UINT64)Address + EPROCESS_PEAK_VIRTUAL_SIZE_OFFSET)) peak_virtual_size = *(UINT64*)((UINT64)Address + EPROCESS_PEAK_VIRTUAL_SIZE_OFFSET); @@ -278,23 +292,24 @@ ValidateIfAddressIsProcessStructure(_In_ PVOID Address, */ STATIC VOID -ScanPageForKernelObjectAllocation(_In_ UINT64 PageBase, - _In_ ULONG PageSize, - _In_ ULONG ObjectIndex, - _Inout_ PPROCESS_SCAN_CONTEXT Context) +ScanPageForKernelObjectAllocation( + _In_ UINT64 PageBase, + _In_ ULONG PageSize, + _In_ ULONG ObjectIndex, + _Inout_ PPROCESS_SCAN_CONTEXT Context) { - INT length = 0; - CHAR current_char = 0; - CHAR current_sig_byte = 0; - PPOOL_HEADER pool_header = NULL; - PEPROCESS process = NULL; - PEPROCESS process_size_one = NULL; - PEPROCESS process_size_two = NULL; - PEPROCESS test_process = NULL; - LPCSTR process_name = NULL; - PUINT64 address_list = NULL; - ULONG allocation_size = 0; - ULONG minimum_process_allocation_size = + INT length = 0; + CHAR current_char = 0; + CHAR current_sig_byte = 0; + PPOOL_HEADER pool_header = NULL; + PEPROCESS process = NULL; + PEPROCESS process_size_one = NULL; + PEPROCESS process_size_two = NULL; + PEPROCESS test_process = NULL; + LPCSTR process_name = NULL; + PUINT64 address_list = NULL; + ULONG allocation_size = 0; + ULONG minimum_process_allocation_size = EPROCESS_SIZE - sizeof(POOL_HEADER) - OBJECT_HEADER_SIZE; if (!PageBase || !PageSize) @@ -335,8 +350,9 @@ ScanPageForKernelObjectAllocation(_In_ UINT64 PageBase, (PEPROCESS)((UINT64)pool_header + sizeof(POOL_HEADER) + header_size); - if (ValidateIfAddressIsProcessStructure(test_process, - pool_header)) { + if (ValidateIfAddressIsProcessStructure( + test_process, + pool_header)) { process = test_process; break; } @@ -345,8 +361,9 @@ ScanPageForKernelObjectAllocation(_In_ UINT64 PageBase, if (!process) break; - DEBUG_VERBOSE("Found process via pt walk: %llx", - (UINT64)process); + DEBUG_VERBOSE( + "Found process via pt walk: %llx", + (UINT64)process); address_list = (PUINT64)Context->process_buffer; @@ -374,17 +391,17 @@ ScanPageForKernelObjectAllocation(_In_ UINT64 PageBase, */ STATIC BOOLEAN -IsPhysicalAddressInPhysicalMemoryRange(_In_ UINT64 PhysicalAddress, - _In_ PPHYSICAL_MEMORY_RANGE - PhysicalMemoryRanges) +IsPhysicalAddressInPhysicalMemoryRange( + _In_ UINT64 PhysicalAddress, + _In_ PPHYSICAL_MEMORY_RANGE PhysicalMemoryRanges) { - ULONG page_index = 0; + ULONG page_index = 0; UINT64 start_address = 0; - UINT64 end_address = 0; + UINT64 end_address = 0; while (PhysicalMemoryRanges[page_index].NumberOfBytes.QuadPart != NULL) { start_address = PhysicalMemoryRanges[page_index].BaseAddress.QuadPart; - end_address = start_address + + end_address = start_address + PhysicalMemoryRanges[page_index].NumberOfBytes.QuadPart; if (PhysicalAddress >= start_address && PhysicalAddress <= end_address) @@ -398,10 +415,11 @@ IsPhysicalAddressInPhysicalMemoryRange(_In_ UINT64 PhysicalAddress, STATIC VOID -EnumerateKernelLargePages(_In_ UINT64 PageBase, - _In_ ULONG PageSize, - _In_ PPROCESS_SCAN_CONTEXT Context, - _In_ ULONG ObjectIndex) +EnumerateKernelLargePages( + _In_ UINT64 PageBase, + _In_ ULONG PageSize, + _In_ PPROCESS_SCAN_CONTEXT Context, + _In_ ULONG ObjectIndex) { /* * Split the large pages up into blocks of 0x1000 and scan each block @@ -409,7 +427,10 @@ EnumerateKernelLargePages(_In_ UINT64 PageBase, for (UINT64 page_index = 0; page_index < PageSize; page_index++) { UINT64 page_base = PageBase + (page_index * PAGE_SIZE); ScanPageForKernelObjectAllocation( - page_base, PAGE_SIZE, ObjectIndex, Context); + page_base, + PAGE_SIZE, + ObjectIndex, + Context); } } @@ -445,24 +466,24 @@ STATIC VOID WalkKernelPageTables(_In_ PPROCESS_SCAN_CONTEXT Context) { - CR3 cr3 = {0}; - PML4E pml4_base = {0}; - PML4E pml4_entry = {0}; - UINT64 pdpt_base = 0; - UINT64 pd_base = 0; - UINT64 pt_base = 0; - PDPTE pdpt_entry = {0}; - PDPTE_LARGE pdpt_large_entry = {0}; - PDE pd_entry = {0}; - PDE_LARGE pd_large_entry = {0}; - PTE pt_entry = {0}; - UINT64 base_physical_page = 0; - UINT64 base_virtual_page = 0; - UINT64 base_2mb_virtual_page = 0; - UINT64 base_1gb_virtual_page = 0; - PHYSICAL_ADDRESS physical = {0}; + CR3 cr3 = {0}; + PML4E pml4_base = {0}; + PML4E pml4_entry = {0}; + UINT64 pdpt_base = 0; + UINT64 pd_base = 0; + UINT64 pt_base = 0; + PDPTE pdpt_entry = {0}; + PDPTE_LARGE pdpt_large_entry = {0}; + PDE pd_entry = {0}; + PDE_LARGE pd_large_entry = {0}; + PTE pt_entry = {0}; + UINT64 base_physical_page = 0; + UINT64 base_virtual_page = 0; + UINT64 base_2mb_virtual_page = 0; + UINT64 base_1gb_virtual_page = 0; + PHYSICAL_ADDRESS physical = {0}; PPHYSICAL_MEMORY_RANGE physical_memory_ranges = NULL; - KIRQL irql = {0}; + KIRQL irql = {0}; physical_memory_ranges = ImpMmGetPhysicalMemoryRangesEx2(NULL, NULL); @@ -481,8 +502,8 @@ WalkKernelPageTables(_In_ PPROCESS_SCAN_CONTEXT Context) return; for (INT pml4_index = 0; pml4_index < PML4_ENTRY_COUNT; pml4_index++) { - if (!ImpMmIsAddressValid(pml4_base.BitAddress + - pml4_index * sizeof(UINT64))) + if (!ImpMmIsAddressValid( + pml4_base.BitAddress + pml4_index * sizeof(UINT64))) continue; pml4_entry.BitAddress = @@ -516,7 +537,8 @@ WalkKernelPageTables(_In_ PPROCESS_SCAN_CONTEXT Context) << PAGE_1GB_SHIFT; if (IsPhysicalAddressInPhysicalMemoryRange( - physical.QuadPart, physical_memory_ranges) == FALSE) + physical.QuadPart, + physical_memory_ranges) == FALSE) continue; base_1gb_virtual_page = ImpMmGetVirtualForPhysical(physical); @@ -525,10 +547,11 @@ WalkKernelPageTables(_In_ PPROCESS_SCAN_CONTEXT Context) !ImpMmIsAddressValid(base_1gb_virtual_page)) continue; - EnumerateKernelLargePages(base_1gb_virtual_page, - LARGE_PAGE_1GB_ENTRIES, - Context, - INDEX_PROCESS_POOL_TAG); + EnumerateKernelLargePages( + base_1gb_virtual_page, + LARGE_PAGE_1GB_ENTRIES, + Context, + INDEX_PROCESS_POOL_TAG); continue; } @@ -559,7 +582,8 @@ WalkKernelPageTables(_In_ PPROCESS_SCAN_CONTEXT Context) << PAGE_2MB_SHIFT; if (IsPhysicalAddressInPhysicalMemoryRange( - physical.QuadPart, physical_memory_ranges) == FALSE) + physical.QuadPart, + physical_memory_ranges) == FALSE) continue; base_2mb_virtual_page = @@ -569,10 +593,11 @@ WalkKernelPageTables(_In_ PPROCESS_SCAN_CONTEXT Context) !ImpMmIsAddressValid(base_2mb_virtual_page)) continue; - EnumerateKernelLargePages(base_2mb_virtual_page, - LARGE_PAGE_2MB_ENTRIES, - Context, - INDEX_PROCESS_POOL_TAG); + EnumerateKernelLargePages( + base_2mb_virtual_page, + LARGE_PAGE_2MB_ENTRIES, + Context, + INDEX_PROCESS_POOL_TAG); continue; } @@ -589,8 +614,8 @@ WalkKernelPageTables(_In_ PPROCESS_SCAN_CONTEXT Context) continue; for (INT pt_index = 0; pt_index < PT_ENTRY_COUNT; pt_index++) { - if (!ImpMmIsAddressValid(pt_base + - pt_index * sizeof(UINT64))) + if (!ImpMmIsAddressValid( + pt_base + pt_index * sizeof(UINT64))) continue; pt_entry.BitAddress = @@ -605,7 +630,8 @@ WalkKernelPageTables(_In_ PPROCESS_SCAN_CONTEXT Context) /* if the page base isnt in a legit * region, go next */ if (IsPhysicalAddressInPhysicalMemoryRange( - physical.QuadPart, physical_memory_ranges) == FALSE) + physical.QuadPart, + physical_memory_ranges) == FALSE) continue; base_virtual_page = ImpMmGetVirtualForPhysical(physical); @@ -616,10 +642,11 @@ WalkKernelPageTables(_In_ PPROCESS_SCAN_CONTEXT Context) !ImpMmIsAddressValid(base_virtual_page)) continue; - ScanPageForKernelObjectAllocation(base_virtual_page, - PAGE_BASE_SIZE, - INDEX_PROCESS_POOL_TAG, - Context); + ScanPageForKernelObjectAllocation( + base_virtual_page, + PAGE_BASE_SIZE, + INDEX_PROCESS_POOL_TAG, + Context); } } } @@ -646,13 +673,13 @@ IncrementProcessCounter(_In_ PPROCESS_LIST_ENTRY Node, _In_opt_ PVOID Context) STATIC VOID -CheckIfProcessAllocationIsInProcessList(_In_ PPROCESS_LIST_ENTRY Node, - _In_opt_ PVOID Context) +CheckIfProcessAllocationIsInProcessList( + _In_ PPROCESS_LIST_ENTRY Node, _In_opt_ PVOID Context) { PAGED_CODE(); - PUINT64 allocation_address = NULL; - PPROCESS_SCAN_CONTEXT context = (PPROCESS_SCAN_CONTEXT)Context; + PUINT64 allocation_address = NULL; + PPROCESS_SCAN_CONTEXT context = (PPROCESS_SCAN_CONTEXT)Context; if (!context) return; @@ -664,8 +691,9 @@ CheckIfProcessAllocationIsInProcessList(_In_ PPROCESS_LIST_ENTRY Node, allocation_address[i] - PROCESS_OBJECT_ALLOCATION_MARGIN && (UINT64)Node->process <= allocation_address[i] + PROCESS_OBJECT_ALLOCATION_MARGIN) { - RtlZeroMemory((UINT64)context->process_buffer + i * sizeof(UINT64), - sizeof(UINT64)); + RtlZeroMemory( + (UINT64)context->process_buffer + i * sizeof(UINT64), + sizeof(UINT64)); } } } @@ -679,10 +707,10 @@ FindUnlinkedProcesses() { PAGED_CODE(); - NTSTATUS status = STATUS_UNSUCCESSFUL; - PUINT64 allocation_address = NULL; - PROCESS_SCAN_CONTEXT context = {0}; - PINVALID_PROCESS_ALLOCATION_REPORT report = NULL; + NTSTATUS status = STATUS_UNSUCCESSFUL; + PUINT64 allocation_address = NULL; + PROCESS_SCAN_CONTEXT context = {0}; + PINVALID_PROCESS_ALLOCATION_REPORT report = NULL; UINT32 packet_size = CryptRequestRequiredBufferLength( sizeof(INVALID_PROCESS_ALLOCATION_REPORT)); @@ -693,10 +721,10 @@ FindUnlinkedProcesses() return STATUS_ABANDONED; } - context.process_buffer = - ExAllocatePool2(POOL_FLAG_NON_PAGED, - context.process_count * 2 * sizeof(UINT64), - PROCESS_ADDRESS_LIST_TAG); + context.process_buffer = ExAllocatePool2( + POOL_FLAG_NON_PAGED, + context.process_count * 2 * sizeof(UINT64), + PROCESS_ADDRESS_LIST_TAG); if (!context.process_buffer) return STATUS_MEMORY_NOT_ALLOCATED; @@ -704,7 +732,9 @@ FindUnlinkedProcesses() WalkKernelPageTables(&context); RtlHashmapEnumerate( - GetProcessHashmap(), CheckIfProcessAllocationIsInProcessList, &context); + GetProcessHashmap(), + CheckIfProcessAllocationIsInProcessList, + &context); allocation_address = (PUINT64)context.process_buffer; @@ -727,7 +757,9 @@ FindUnlinkedProcesses() allocation); report = ImpExAllocatePool2( - POOL_FLAG_NON_PAGED, packet_size, REPORT_POOL_TAG); + POOL_FLAG_NON_PAGED, + packet_size, + REPORT_POOL_TAG); if (!report) continue; @@ -735,7 +767,9 @@ FindUnlinkedProcesses() INIT_REPORT_PACKET(report, REPORT_INVALID_PROCESS_ALLOCATION, 0); IntCopyMemory( - report->process, allocation, REPORT_INVALID_PROCESS_BUFFER_SIZE); + report->process, + allocation, + REPORT_INVALID_PROCESS_BUFFER_SIZE); status = CryptEncryptBuffer(report, packet_size); @@ -764,11 +798,11 @@ end: NTSTATUS EnumerateBigPoolAllocations() { - ULONG return_length = 0; - NTSTATUS status = STATUS_UNSUCCESSFUL; - PSYSTEM_BIGPOOL_ENTRY entry = NULL; - SYSTEM_BIGPOOL_INFORMATION pool_information = {0}; - PSYSTEM_BIGPOOL_INFORMATION pool_entries = NULL; + ULONG return_length = 0; + NTSTATUS status = STATUS_UNSUCCESSFUL; + PSYSTEM_BIGPOOL_ENTRY entry = NULL; + SYSTEM_BIGPOOL_INFORMATION pool_information = {0}; + PSYSTEM_BIGPOOL_INFORMATION pool_entries = NULL; UNICODE_STRING routine = RTL_CONSTANT_STRING(L"ZwQuerySystemInformation"); ZwQuerySystemInformation pZwQuerySystemInformation = ImpMmGetSystemRoutineAddress(&routine); @@ -778,10 +812,11 @@ EnumerateBigPoolAllocations() return status; } - status = pZwQuerySystemInformation(SYSTEM_BIGPOOL_INFORMATION_ID, - &pool_information, - sizeof(pool_information), - &return_length); + status = pZwQuerySystemInformation( + SYSTEM_BIGPOOL_INFORMATION_ID, + &pool_information, + sizeof(pool_information), + &return_length); if (status != STATUS_INFO_LENGTH_MISMATCH) { DEBUG_ERROR("ZwQuerySystemInformation failed with status %x", status); @@ -791,15 +826,18 @@ EnumerateBigPoolAllocations() return_length += sizeof(SYSTEM_BIGPOOL_INFORMATION); pool_entries = ImpExAllocatePool2( - POOL_FLAG_NON_PAGED, return_length, POOL_TAG_INTEGRITY); + POOL_FLAG_NON_PAGED, + return_length, + POOL_TAG_INTEGRITY); if (!pool_entries) return STATUS_MEMORY_NOT_ALLOCATED; - status = pZwQuerySystemInformation(SYSTEM_BIGPOOL_INFORMATION_ID, - pool_entries, - return_length, - &return_length); + status = pZwQuerySystemInformation( + SYSTEM_BIGPOOL_INFORMATION_ID, + pool_entries, + return_length, + &return_length); if (!NT_SUCCESS(status)) { DEBUG_ERROR("ZwQuerySystemInformation 2 failed with status %x", status); diff --git a/driver/session.c b/driver/session.c index 9540b50..a70d140 100644 --- a/driver/session.c +++ b/driver/session.c @@ -1,7 +1,7 @@ #include "session.h" -#include "imports.h" #include "crypt.h" +#include "imports.h" #include "util.h" #include "lib/stdlib.h" @@ -9,7 +9,7 @@ NTSTATUS SessionInitialiseStructure() { - NTSTATUS status = STATUS_UNSUCCESSFUL; + NTSTATUS status = STATUS_UNSUCCESSFUL; PACTIVE_SESSION session = GetActiveSession(); KeInitializeGuardedMutex(&session->lock); @@ -74,12 +74,12 @@ SessionTerminate() DEBUG_INFO("Termination active session."); PACTIVE_SESSION session = GetActiveSession(); - KIRQL irql = {0}; + KIRQL irql = {0}; KeAcquireGuardedMutex(&session->lock); - session->km_handle = NULL; - session->um_handle = NULL; - session->process = NULL; + session->km_handle = NULL; + session->um_handle = NULL; + session->process = NULL; session->is_session_active = FALSE; RtlZeroMemory(&session->module, sizeof(MODULE_INFORMATION)); @@ -92,18 +92,19 @@ SessionTerminate() /* Return type for this doesnt matter */ STATIC BOOLEAN -HashOurUserModuleOnEntryCallback(_In_ PPROCESS_MAP_MODULE_ENTRY Entry, - _In_opt_ PVOID Context) +HashOurUserModuleOnEntryCallback( + _In_ PPROCESS_MAP_MODULE_ENTRY Entry, _In_opt_ PVOID Context) { - NTSTATUS status = STATUS_UNSUCCESSFUL; + NTSTATUS status = STATUS_UNSUCCESSFUL; PACTIVE_SESSION session = (PACTIVE_SESSION)Context; if (!ARGUMENT_PRESENT(Context)) return FALSE; - status = HashUserModule(Entry, - session->module.module_hash, - sizeof(session->module.module_hash)); + status = HashUserModule( + Entry, + session->module.module_hash, + sizeof(session->module.module_hash)); if (!NT_SUCCESS(status)) { DEBUG_ERROR("HashUserModule: %lx", status); @@ -111,8 +112,9 @@ HashOurUserModuleOnEntryCallback(_In_ PPROCESS_MAP_MODULE_ENTRY Entry, } DEBUG_VERBOSE("User module hashed!"); - DumpBufferToKernelDebugger(session->module.module_hash, - sizeof(session->module.module_hash)); + DumpBufferToKernelDebugger( + session->module.module_hash, + sizeof(session->module.module_hash)); return TRUE; } @@ -120,16 +122,17 @@ HashOurUserModuleOnEntryCallback(_In_ PPROCESS_MAP_MODULE_ENTRY Entry, NTSTATUS SessionInitialise(_In_ PIRP Irp) { - NTSTATUS status = STATUS_UNSUCCESSFUL; - PEPROCESS process = NULL; + NTSTATUS status = STATUS_UNSUCCESSFUL; + PEPROCESS process = NULL; PSESSION_INITIATION_PACKET initiation = NULL; - PACTIVE_SESSION session = GetActiveSession(); - KIRQL irql = {0}; + PACTIVE_SESSION session = GetActiveSession(); + KIRQL irql = {0}; DEBUG_VERBOSE("Initialising new session."); status = ValidateIrpInputBuffer( - Irp, sizeof(SESSION_INITIATION_PACKET) - SHA_256_HASH_LENGTH); + Irp, + sizeof(SESSION_INITIATION_PACKET) - SHA_256_HASH_LENGTH); if (!NT_SUCCESS(status)) { DEBUG_ERROR("ValidateIrpInputBuffer failed with status %x", status); @@ -151,17 +154,19 @@ SessionInitialise(_In_ PIRP Irp) } session->km_handle = ImpPsGetProcessId(process); - session->process = process; - session->cookie = initiation->cookie; + session->process = process; + session->cookie = initiation->cookie; IntCopyMemory(session->aes_key, initiation->aes_key, AES_256_KEY_SIZE); IntCopyMemory(session->iv, initiation->aes_iv, AES_256_IV_SIZE); session->module.base_address = initiation->module_info.base_address; - session->module.size = initiation->module_info.size; + session->module.size = initiation->module_info.size; IntCopyMemory( - session->module.path, initiation->module_info.path, MAX_MODULE_PATH); + session->module.path, + initiation->module_info.path, + MAX_MODULE_PATH); DEBUG_VERBOSE("Module base: %llx", session->module.base_address); DEBUG_VERBOSE("Module size: %lx ", session->module.size); @@ -193,8 +198,8 @@ end: VOID SessionTerminateProcess() { - NTSTATUS status = STATUS_UNSUCCESSFUL; - ULONG process_id = 0; + NTSTATUS status = STATUS_UNSUCCESSFUL; + ULONG process_id = 0; SessionGetProcessId(&process_id); @@ -205,8 +210,9 @@ SessionTerminateProcess() /* Make sure we pass a km handle to ZwTerminateProcess and NOT a * usermode handle. */ - status = ZwTerminateProcess(process_id, - STATUS_SYSTEM_INTEGRITY_POLICY_VIOLATION); + status = ZwTerminateProcess( + process_id, + STATUS_SYSTEM_INTEGRITY_POLICY_VIOLATION); if (!NT_SUCCESS(status)) { /* diff --git a/driver/thread.c b/driver/thread.c index 624ee1a..e1f6380 100644 --- a/driver/thread.c +++ b/driver/thread.c @@ -2,14 +2,14 @@ #include -#include "pool.h" #include "callbacks.h" #include "driver.h" +#include "pool.h" -#include "session.h" -#include "imports.h" #include "containers/tree.h" #include "crypt.h" +#include "imports.h" +#include "session.h" #include "lib/stdlib.h" @@ -23,9 +23,9 @@ DoesThreadHaveValidCidEntry(_In_ PETHREAD Thread) { PAGED_CODE(); - NTSTATUS status = STATUS_UNSUCCESSFUL; - HANDLE thread_id = NULL; - PETHREAD thread = NULL; + NTSTATUS status = STATUS_UNSUCCESSFUL; + HANDLE thread_id = NULL; + PETHREAD thread = NULL; /* * PsGetThreadId simply returns ETHREAD->Cid.UniqueThread @@ -80,15 +80,15 @@ DoesThreadHaveValidCidEntry(_In_ PETHREAD Thread) * any APC's queued. */ STATIC VOID -DetectAttachedThreadsProcessCallback(_In_ PTHREAD_LIST_ENTRY ThreadListEntry, - _Inout_opt_ PVOID Context) +DetectAttachedThreadsProcessCallback( + _In_ PTHREAD_LIST_ENTRY ThreadListEntry, _Inout_opt_ PVOID Context) { UNREFERENCED_PARAMETER(Context); - NTSTATUS status = STATUS_UNSUCCESSFUL; - PKAPC_STATE apc_state = NULL; - PEPROCESS protected_process = NULL; - UINT32 packet_size = + NTSTATUS status = STATUS_UNSUCCESSFUL; + PKAPC_STATE apc_state = NULL; + PEPROCESS protected_process = NULL; + UINT32 packet_size = CryptRequestRequiredBufferLength(sizeof(ATTACH_PROCESS_REPORT)); SessionGetProcess(&protected_process); @@ -110,8 +110,9 @@ DetectAttachedThreadsProcessCallback(_In_ PTHREAD_LIST_ENTRY ThreadListEntry, return; } - DEBUG_WARNING("Thread is attached to our protected process: %llx", - (UINT64)ThreadListEntry->thread); + DEBUG_WARNING( + "Thread is attached to our protected process: %llx", + (UINT64)ThreadListEntry->thread); PATTACH_PROCESS_REPORT report = ImpExAllocatePool2(POOL_FLAG_NON_PAGED, packet_size, REPORT_POOL_TAG); @@ -121,7 +122,7 @@ DetectAttachedThreadsProcessCallback(_In_ PTHREAD_LIST_ENTRY ThreadListEntry, INIT_REPORT_PACKET(report, REPORT_ILLEGAL_ATTACH_PROCESS, 0); - report->thread_id = ImpPsGetThreadId(ThreadListEntry->thread); + report->thread_id = ImpPsGetThreadId(ThreadListEntry->thread); report->thread_address = ThreadListEntry->thread; status = CryptEncryptBuffer(report, packet_size); @@ -141,5 +142,7 @@ DetectThreadsAttachedToProtectedProcess() PAGED_CODE(); DEBUG_VERBOSE("Detecting threads attached to our process..."); RtlRbTreeEnumerate( - GetThreadTree(), DetectAttachedThreadsProcessCallback, NULL); + GetThreadTree(), + DetectAttachedThreadsProcessCallback, + NULL); } diff --git a/driver/util.c b/driver/util.c index ace82e3..27c6a0a 100644 --- a/driver/util.c +++ b/driver/util.c @@ -6,8 +6,8 @@ LARGE_INTEGER GenerateRandSeed() { LARGE_INTEGER system_time = {0}; - LARGE_INTEGER up_time = {0}; - LARGE_INTEGER seed = {0}; + LARGE_INTEGER up_time = {0}; + LARGE_INTEGER seed = {0}; KeQuerySystemTime(&system_time); KeQueryTickCount(&up_time); @@ -17,12 +17,13 @@ GenerateRandSeed() } NTSTATUS -MapAndReadPhysical(_In_ UINT64 PhysicalAddress, - _In_ UINT32 ReadLength, - _Out_ PVOID OutputBuffer, - _In_ UINT32 OutputBufferLength) +MapAndReadPhysical( + _In_ UINT64 PhysicalAddress, + _In_ UINT32 ReadLength, + _Out_ PVOID OutputBuffer, + _In_ UINT32 OutputBufferLength) { - PVOID va = NULL; + PVOID va = NULL; PHYSICAL_ADDRESS pa = {.QuadPart = PhysicalAddress}; if (ReadLength > OutputBufferLength) @@ -45,12 +46,13 @@ MapAndReadPhysical(_In_ UINT64 PhysicalAddress, } NTSTATUS -UnicodeToCharBufString(_In_ PUNICODE_STRING UnicodeString, - _Out_ PVOID OutBuffer, - _In_ UINT32 OutBufferSize) +UnicodeToCharBufString( + _In_ PUNICODE_STRING UnicodeString, + _Out_ PVOID OutBuffer, + _In_ UINT32 OutBufferSize) { ANSI_STRING string = {0}; - NTSTATUS status = STATUS_UNSUCCESSFUL; + NTSTATUS status = STATUS_UNSUCCESSFUL; status = RtlUnicodeStringToAnsiString(&string, UnicodeString, TRUE);