diff options
Diffstat (limited to 'PastDSEDriver')
-rw-r--r-- | PastDSEDriver/BlackBone.c | 475 | ||||
-rw-r--r-- | PastDSEDriver/BlackBoneLoaderReloc.c | 395 | ||||
-rw-r--r-- | PastDSEDriver/Driver.c | 150 | ||||
-rw-r--r-- | PastDSEDriver/Driver.h | 154 | ||||
-rw-r--r-- | PastDSEDriver/Imports.h | 58 | ||||
-rw-r--r-- | PastDSEDriver/Native.h | 242 | ||||
-rw-r--r-- | PastDSEDriver/PE.h | 293 | ||||
-rw-r--r-- | PastDSEDriver/PastDSEDriver.vcxproj | 125 | ||||
-rw-r--r-- | PastDSEDriver/PastDSEDriver.vcxproj.filters | 43 | ||||
-rw-r--r-- | PastDSEDriver/Utils.c | 129 |
10 files changed, 2064 insertions, 0 deletions
diff --git a/PastDSEDriver/BlackBone.c b/PastDSEDriver/BlackBone.c new file mode 100644 index 0000000..026421e --- /dev/null +++ b/PastDSEDriver/BlackBone.c @@ -0,0 +1,475 @@ +/****************************************************** +* FILENAME: +* BlackBoned.c +* +* DESCRIPTION: +* Driver utility functions. +* +* Copyright Toni Uhlig 2019. All rights reserved. +* +* AUTHOR: +* DarthTon +* Toni Uhlig START DATE : 27 Mar 19 +*/ + +#include "Driver.h" +#include "Imports.h" +#include "PE.h" +#include "Native.h" + + +PLIST_ENTRY PsLoadedModuleList; + +#pragma alloc_test(PAGE, BBInitLdrData) +#pragma alloc_text(PAGE, BBGetModuleExport) +#pragma alloc_text(PAGE, BBGetSystemModule) +#pragma alloc_text(PAGE, BBSafeInitString) +#pragma alloc_text(PAGE, BBResolveImageRefs) +#pragma alloc_text(PAGE, BBCreateCookie) +#pragma alloc_text(PAGE, BBMapWorker) +#pragma alloc_text(PAGE, BBMMapDriver) + + +NTSTATUS BBInitLdrData(IN PKLDR_DATA_TABLE_ENTRY pThisModule) +{ + PVOID kernelBase = GetKernelBase(NULL); + if (kernelBase == NULL) + { + KDBG("Failed to retrieve Kernel base address. Aborting\n"); + return STATUS_NOT_FOUND; + } + + // Get PsLoadedModuleList address + for (PLIST_ENTRY pListEntry = pThisModule->InLoadOrderLinks.Flink; pListEntry != &pThisModule->InLoadOrderLinks; pListEntry = pListEntry->Flink) + { + // Search for Ntoskrnl entry + PKLDR_DATA_TABLE_ENTRY pEntry = CONTAINING_RECORD(pListEntry, KLDR_DATA_TABLE_ENTRY, InLoadOrderLinks); + if (kernelBase == pEntry->DllBase) + { + // Ntoskrnl is always first entry in the list + // Check if found pointer belongs to Ntoskrnl module + if ((PVOID)pListEntry->Blink >= pEntry->DllBase && (PUCHAR)pListEntry->Blink < (PUCHAR)pEntry->DllBase + pEntry->SizeOfImage) + { + PsLoadedModuleList = pListEntry->Blink; + break; + } + } + } + + if (!PsLoadedModuleList) + { + KDBG("Failed to retrieve PsLoadedModuleList address. Aborting\n"); + return STATUS_NOT_FOUND; + } + + return STATUS_SUCCESS; +} + +PVOID BBGetModuleExport(IN PVOID pBase, IN PCCHAR name_ord) +{ + PIMAGE_DOS_HEADER pDosHdr = (PIMAGE_DOS_HEADER)pBase; + PIMAGE_NT_HEADERS64 pNtHdr64 = NULL; + PIMAGE_EXPORT_DIRECTORY pExport = NULL; + ULONG expSize = 0; + ULONG_PTR pAddress = 0; + + ASSERT(pBase != NULL); + if (pBase == NULL) + return NULL; + + /// Not a PE file + if (pDosHdr->e_magic != IMAGE_DOS_SIGNATURE) + return NULL; + + pNtHdr64 = (PIMAGE_NT_HEADERS64)((PUCHAR)pBase + pDosHdr->e_lfanew); + + // Not a PE file + if (pNtHdr64->Signature != IMAGE_NT_SIGNATURE) + return NULL; + + // 64 bit image + if (pNtHdr64->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC) + { + pExport = (PIMAGE_EXPORT_DIRECTORY)(pNtHdr64->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress + (ULONG_PTR)pBase); + expSize = pNtHdr64->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size; + } + // 32 bit image + else return NULL; + + PUSHORT pAddressOfOrds = (PUSHORT)(pExport->AddressOfNameOrdinals + (ULONG_PTR)pBase); + PULONG pAddressOfNames = (PULONG)(pExport->AddressOfNames + (ULONG_PTR)pBase); + PULONG pAddressOfFuncs = (PULONG)(pExport->AddressOfFunctions + (ULONG_PTR)pBase); + + for (ULONG i = 0; i < pExport->NumberOfFunctions; ++i) + { + USHORT OrdIndex = 0xFFFF; + PCHAR pName = NULL; + + // Find by index + if ((ULONG_PTR)name_ord <= 0xFFFF) + { + OrdIndex = (USHORT)i; + } + // Find by name + else if ((ULONG_PTR)name_ord > 0xFFFF && i < pExport->NumberOfNames) + { + pName = (PCHAR)(pAddressOfNames[i] + (ULONG_PTR)pBase); + OrdIndex = pAddressOfOrds[i]; + } + // Weird params + else + return NULL; + + if (((ULONG_PTR)name_ord <= 0xFFFF && (USHORT)((ULONG_PTR)name_ord) == OrdIndex + pExport->Base) || + ((ULONG_PTR)name_ord > 0xFFFF && strcmp(pName, name_ord) == 0)) + { + pAddress = pAddressOfFuncs[OrdIndex] + (ULONG_PTR)pBase; + + if (pAddress >= (ULONG_PTR)pExport && pAddress <= (ULONG_PTR)pExport + expSize) + return NULL; + break; + } + } + + return (PVOID)pAddress; +} + +PKLDR_DATA_TABLE_ENTRY BBGetSystemModule(IN PUNICODE_STRING pName, IN PVOID pAddress) +{ + ASSERT((pName != NULL || pAddress != NULL) && PsLoadedModuleList != NULL); + if ((pName == NULL && pAddress == NULL) || PsLoadedModuleList == NULL) + return NULL; + + // No images + if (IsListEmpty(PsLoadedModuleList)) + return NULL; + + // Search in PsLoadedModuleList + for (PLIST_ENTRY pListEntry = PsLoadedModuleList->Flink; pListEntry != PsLoadedModuleList; pListEntry = pListEntry->Flink) + { + PKLDR_DATA_TABLE_ENTRY pEntry = CONTAINING_RECORD(pListEntry, KLDR_DATA_TABLE_ENTRY, InLoadOrderLinks); + + // Check by name or by address + if ((pName && RtlCompareUnicodeString(&pEntry->BaseDllName, pName, TRUE) == 0) || + (pAddress && pAddress >= pEntry->DllBase && (PUCHAR)pAddress < (PUCHAR)pEntry->DllBase + pEntry->SizeOfImage)) + { + return pEntry; + } + } + + return NULL; +} + +NTSTATUS BBSafeInitString(OUT PUNICODE_STRING result, IN PUNICODE_STRING source) +{ + ASSERT(result != NULL && source != NULL); + if (result == NULL || source == NULL || source->Buffer == NULL) + return STATUS_INVALID_PARAMETER; + + // No data to copy + if (source->Length == 0) + { + result->Length = result->MaximumLength = 0; + result->Buffer = NULL; + return STATUS_SUCCESS; + } + + result->Buffer = ExAllocatePoolWithTag(PagedPool, source->MaximumLength, PASTDSE_POOL_TAG); + result->Length = source->Length; + result->MaximumLength = source->MaximumLength; + + memcpy(result->Buffer, source->Buffer, source->Length); + + return STATUS_SUCCESS; +} + +NTSTATUS BBResolveImageRefs(IN PVOID pImageBase) +{ + NTSTATUS status = STATUS_SUCCESS; + ULONG impSize = 0; + PIMAGE_IMPORT_DESCRIPTOR pImportTbl = RtlImageDirectoryEntryToData(pImageBase, TRUE, IMAGE_DIRECTORY_ENTRY_IMPORT, &impSize); + + // No import libs + if (pImportTbl == NULL) + return STATUS_SUCCESS; + + for (; pImportTbl->Name && NT_SUCCESS(status); ++pImportTbl) + { + PVOID pThunk = ((PUCHAR)pImageBase + (pImportTbl->OriginalFirstThunk ? pImportTbl->OriginalFirstThunk : pImportTbl->FirstThunk)); + UNICODE_STRING ustrImpDll = { 0 }; + UNICODE_STRING resolved = { 0 }; + ANSI_STRING strImpDll = { 0 }; + ULONG IAT_Index = 0; + PCCHAR impFunc = NULL; + union + { + PVOID address; + PKLDR_DATA_TABLE_ENTRY ldrEntry; + } pModule = { 0 }; + + RtlInitAnsiString(&strImpDll, (PCHAR)pImageBase + pImportTbl->Name); + RtlAnsiStringToUnicodeString(&ustrImpDll, &strImpDll, TRUE); + + // Resolve image name + BBSafeInitString(&resolved, &ustrImpDll); + + // Get import module + pModule.address = BBGetSystemModule(&ustrImpDll, NULL); + + // Failed to load + if (!pModule.address) + { + KDBG("Failed to load import '%wZ'. Status code: 0x%X\n", ustrImpDll, status); + RtlFreeUnicodeString(&ustrImpDll); + RtlFreeUnicodeString(&resolved); + + return STATUS_NOT_FOUND; + } + + while (THUNK_VAL_T(pHeader, pThunk, u1.AddressOfData)) + { + PIMAGE_IMPORT_BY_NAME pAddressTable = (PIMAGE_IMPORT_BY_NAME)((PUCHAR)pImageBase + THUNK_VAL_T(pHeader, pThunk, u1.AddressOfData)); + PVOID pFunc = NULL; + + // import by name + if (THUNK_VAL_T(pHeader, pThunk, u1.AddressOfData) < IMAGE_ORDINAL_FLAG64 && + pAddressTable->Name[0]) + { + impFunc = pAddressTable->Name; + } + // import by ordinal + else + { + impFunc = (PCCHAR)(THUNK_VAL_T(pHeader, pThunk, u1.AddressOfData) & 0xFFFF); + } + + pFunc = BBGetModuleExport(pModule.ldrEntry->DllBase, impFunc); + + // No export found + if (!pFunc) + { + if (THUNK_VAL_T(pHeader, pThunk, u1.AddressOfData) < IMAGE_ORDINAL_FLAG64 && pAddressTable->Name[0]) + KDBG("Failed to resolve import '%wZ' : '%s'\n", ustrImpDll, pAddressTable->Name); + else + KDBG("Failed to resolve import '%wZ' : '%d'\n", ustrImpDll, THUNK_VAL_T(pHeader, pThunk, u1.AddressOfData) & 0xFFFF); + + status = STATUS_NOT_FOUND; + break; + } + + // Save address to IAT + if (pImportTbl->FirstThunk) + *(PULONG_PTR)((PUCHAR)pImageBase + pImportTbl->FirstThunk + IAT_Index) = (ULONG_PTR)pFunc; + // Save address to OrigianlFirstThunk + else + *(PULONG_PTR)((PUCHAR)pImageBase + THUNK_VAL_T(pHeader, pThunk, u1.AddressOfData)) = (ULONG_PTR)pFunc; + + // Go to next entry + pThunk = (PUCHAR)pThunk + sizeof(IMAGE_THUNK_DATA64); + IAT_Index += sizeof(ULONGLONG); + } + + RtlFreeUnicodeString(&ustrImpDll); + RtlFreeUnicodeString(&resolved); + } + + return status; +} + +NTSTATUS BBCreateCookie(IN PVOID imageBase) +{ + NTSTATUS status = STATUS_SUCCESS; + PIMAGE_NT_HEADERS pHeader = RtlImageNtHeader(imageBase); + if (pHeader) + { + ULONG cfgSize = 0; + PVOID pCfgDir = RtlImageDirectoryEntryToData(imageBase, TRUE, IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG, &cfgSize); + + // TODO: implement proper cookie algorithm + if (pCfgDir && CFG_DIR_VAL_T(pHeader, pCfgDir, SecurityCookie)) + { + ULONG seed = (ULONG)(ULONG_PTR)imageBase ^ (ULONG)((ULONG_PTR)imageBase >> 32); + ULONG_PTR cookie = (ULONG_PTR)imageBase ^ RtlRandomEx(&seed); + + // SecurityCookie value must be rebased by this moment + *(PULONG_PTR)CFG_DIR_VAL_T(pHeader, pCfgDir, SecurityCookie) = cookie; + } + } + else + status = STATUS_INVALID_IMAGE_FORMAT; + + return status; +} + +NTSTATUS BBMapWorker(IN PVOID pArg) +{ + NTSTATUS status = STATUS_SUCCESS, drvinit_ret; + HANDLE hFile = NULL; + PUNICODE_STRING pPath = (PUNICODE_STRING)pArg; + OBJECT_ATTRIBUTES obAttr = { 0 }; + IO_STATUS_BLOCK statusBlock = { 0 }; + PVOID fileData = NULL; + PIMAGE_NT_HEADERS pNTHeader = NULL; + PVOID imageSection = NULL; + PMDL pMDL = NULL; + FILE_STANDARD_INFORMATION fileInfo = { 0 }; + + InitializeObjectAttributes(&obAttr, pPath, OBJ_KERNEL_HANDLE, NULL, NULL); + + // Open driver file + status = ZwCreateFile( + &hFile, FILE_READ_DATA | SYNCHRONIZE, &obAttr, + &statusBlock, NULL, FILE_ATTRIBUTE_NORMAL, FILE_SHARE_READ, + FILE_OPEN, FILE_SYNCHRONOUS_IO_NONALERT, NULL, 0 + ); + + if (!NT_SUCCESS(status)) + { + KDBG("Failed to open '%wZ'. Status: 0x%X\n", pPath, status); + PsTerminateSystemThread(status); + return status; + } + + // Allocate memory for file contents + status = ZwQueryInformationFile(hFile, &statusBlock, &fileInfo, sizeof(fileInfo), FileStandardInformation); + if (NT_SUCCESS(status)) + fileData = ExAllocatePoolWithTag(PagedPool, fileInfo.EndOfFile.QuadPart, PASTDSE_POOL_TAG); + else + KDBG("Failed to get '%wZ' size. Status: 0x%X\n", pPath, status); + + // Get file contents + status = ZwReadFile(hFile, NULL, NULL, NULL, &statusBlock, fileData, fileInfo.EndOfFile.LowPart, NULL, NULL); + if (NT_SUCCESS(status)) + { + pNTHeader = RtlImageNtHeader(fileData); + if (!pNTHeader) + { + KDBG("Failed to obtaint NT Header for '%wZ'\n", pPath); + status = STATUS_INVALID_IMAGE_FORMAT; + } + } + else + KDBG("Failed to read '%wZ'. Status: 0x%X\n", pPath, status); + + ZwClose(hFile); + + if (NT_SUCCESS(status)) + { + // + // Allocate memory from System PTEs + // + PHYSICAL_ADDRESS start = { 0 }, end = { 0 }; + end.QuadPart = MAXULONG64; + + pMDL = MmAllocatePagesForMdl(start, end, start, pNTHeader->OptionalHeader.SizeOfImage); + imageSection = MmGetSystemAddressForMdlSafe(pMDL, NormalPagePriority); + + if (NT_SUCCESS(status) && imageSection) + { + // Copy header + RtlCopyMemory(imageSection, fileData, pNTHeader->OptionalHeader.SizeOfHeaders); + + // Copy sections + for (PIMAGE_SECTION_HEADER pSection = (PIMAGE_SECTION_HEADER)(pNTHeader + 1); + pSection < (PIMAGE_SECTION_HEADER)(pNTHeader + 1) + pNTHeader->FileHeader.NumberOfSections; + pSection++) + { + RtlCopyMemory( + (PUCHAR)imageSection + pSection->VirtualAddress, + (PUCHAR)fileData + pSection->PointerToRawData, + pSection->SizeOfRawData + ); + } + + // Relocate image + status = LdrRelocateImage(imageSection); + if (!NT_SUCCESS(status)) + KDBG("Failed to relocate image '%wZ'. Status: 0x%X\n", pPath, status); + + // Fill IAT + if (NT_SUCCESS(status)) + status = BBResolveImageRefs(imageSection); + } + else + { + KDBG("Failed to allocate memory for image '%wZ'\n", pPath); + status = STATUS_MEMORY_NOT_ALLOCATED; + } + } + + // Initialize kernel security cookie + if (NT_SUCCESS(status)) + BBCreateCookie(imageSection); + + // Call entry point + if (NT_SUCCESS(status) && pNTHeader->OptionalHeader.AddressOfEntryPoint) + { + PDRIVER_INITIALIZE pEntryPoint = (PDRIVER_INITIALIZE)((ULONG_PTR)imageSection + pNTHeader->OptionalHeader.AddressOfEntryPoint); + drvinit_ret = pEntryPoint(NULL, imageSection); + UNREFERENCED_PARAMETER(drvinit_ret); + KDBG("MMAP driver init returned 0x%X\n", drvinit_ret); + } + + // Wipe header + if (NT_SUCCESS(status) && imageSection) + RandomMemory32(imageSection, pNTHeader->OptionalHeader.SizeOfHeaders); + + // Erase info about allocated region + if (pMDL) + { + // Free image memory in case of failure + if (!NT_SUCCESS(status)) { + MmFreePagesFromMdl(pMDL); + } + ExFreePool(pMDL); + } + + if (fileData) + ExFreePoolWithTag(fileData, PASTDSE_POOL_TAG); + + if (NT_SUCCESS(status)) + KDBG("Successfully mapped '%wZ' at 0x%p\n", pPath, imageSection); + + PsTerminateSystemThread(status); + return status; +} + +NTSTATUS BBMMapDriver(IN PUNICODE_STRING pPath) +{ + HANDLE hThread = NULL; + CLIENT_ID clientID = { 0 }; + OBJECT_ATTRIBUTES obAttr = { 0 }; + PETHREAD pThread = NULL; + OBJECT_HANDLE_INFORMATION handleInfo = { 0 }; + + InitializeObjectAttributes(&obAttr, NULL, OBJ_KERNEL_HANDLE, NULL, NULL); + + ASSERT(pPath != NULL); + if (pPath == NULL) + return STATUS_INVALID_PARAMETER; + + NTSTATUS status = PsCreateSystemThread(&hThread, THREAD_ALL_ACCESS, &obAttr, NULL, &clientID, &BBMapWorker, pPath); + if (!NT_SUCCESS(status)) + { + KDBG("Failed to create worker thread. Status: 0x%X\n", status); + return status; + } + + // Wait on worker thread + status = ObReferenceObjectByHandle(hThread, THREAD_ALL_ACCESS, *PsThreadType, KernelMode, &pThread, &handleInfo); + if (NT_SUCCESS(status)) + { + THREAD_BASIC_INFORMATION info = { 0 }; + ULONG bytes = 0; + + status = KeWaitForSingleObject(pThread, Executive, KernelMode, TRUE, NULL); + status = ZwQueryInformationThread(hThread, ThreadBasicInformation, &info, sizeof(info), &bytes); + if (NT_SUCCESS(status)); + status = info.ExitStatus; + } + + if (pThread) + ObDereferenceObject(pThread); + + return status; +}
\ No newline at end of file diff --git a/PastDSEDriver/BlackBoneLoaderReloc.c b/PastDSEDriver/BlackBoneLoaderReloc.c new file mode 100644 index 0000000..64ccf2f --- /dev/null +++ b/PastDSEDriver/BlackBoneLoaderReloc.c @@ -0,0 +1,395 @@ +/****************************************************** +* FILENAME: +* BlackBonedLoaderReloc.c +* +* DESCRIPTION: +* Driver utility functions. +* +* Copyright Toni Uhlig 2019. All rights reserved. +* +* AUTHOR: +* DarthTon +* Toni Uhlig START DATE : 27 Mar 19 +*/ + +#pragma once + +#include "Driver.h" +#include "PE.h" +#include "Imports.h" + +#include <ntddk.h> + +/*++ + +Copyright (c) Microsoft Corporation. All rights reserved. + +You may only use this code if you agree to the terms of the Windows Research Kernel Source Code License agreement (see License.txt). +If you do not agree to the terms, do not use the code. + + +Module Name: + + ldrreloc.c + +Abstract: + + This module contains the code to relocate an image when + the preferred base isn't available. This is called by the + boot loader, device driver loader, and system loader. + +--*/ + + +// +// Mark a HIGHADJ entry as needing an increment if reprocessing. +// +#define LDRP_RELOCATION_INCREMENT 0x1 + +// +// Mark a HIGHADJ entry as not suitable for reprocessing. +// +#define LDRP_RELOCATION_FINAL 0x2 + + +/* +#pragma alloc_text(PAGE,LdrRelocateImage) +#pragma alloc_text(PAGE,LdrProcessRelocationBlock) +#pragma alloc_text(PAGE,LdrProcessRelocationBlockLongLong)*/ + +NTSTATUS +LdrRelocateImage(__in PVOID NewBase) +{ + LONGLONG Diff; + ULONG TotalCountBytes = 0; + ULONG_PTR VA; + ULONGLONG OldBase; + ULONG SizeOfBlock; + PUSHORT NextOffset = NULL; + PIMAGE_NT_HEADERS NtHeaders; + PIMAGE_BASE_RELOCATION NextBlock; + NTSTATUS Status; + + NtHeaders = RtlImageNtHeader(NewBase); + if (NtHeaders == NULL) { + Status = STATUS_INVALID_IMAGE_FORMAT; + goto Exit; + } + + switch (NtHeaders->OptionalHeader.Magic) { + + case IMAGE_NT_OPTIONAL_HDR64_MAGIC: + + OldBase = + ((PIMAGE_NT_HEADERS64)NtHeaders)->OptionalHeader.ImageBase; + break; + + default: + + Status = STATUS_INVALID_IMAGE_FORMAT; + goto Exit; + } + + // + // Locate the relocation section. + // + + NextBlock = (PIMAGE_BASE_RELOCATION)RtlImageDirectoryEntryToData( + NewBase, TRUE, IMAGE_DIRECTORY_ENTRY_BASERELOC, &TotalCountBytes); + + // + // It is possible for a file to have no relocations, but the relocations + // must not have been stripped. + // + + if (!NextBlock || !TotalCountBytes) + { + Status = (NtHeaders->FileHeader.Characteristics & IMAGE_FILE_RELOCS_STRIPPED) ? STATUS_CONFLICTING_ADDRESSES : STATUS_SUCCESS; + goto Exit; + } + + // + // If the image has a relocation table, then apply the specified fixup + // information to the image. + // + Diff = (ULONG_PTR)NewBase - OldBase; + while (TotalCountBytes) + { + SizeOfBlock = NextBlock->SizeOfBlock; + + // Prevent crash + if (SizeOfBlock == 0) + { + Status = STATUS_INVALID_IMAGE_FORMAT; + goto Exit; + } + + TotalCountBytes -= SizeOfBlock; + SizeOfBlock -= sizeof(IMAGE_BASE_RELOCATION); + SizeOfBlock /= sizeof(USHORT); + NextOffset = (PUSHORT)((PCHAR)NextBlock + sizeof(IMAGE_BASE_RELOCATION)); + + VA = (ULONG_PTR)NewBase + NextBlock->VirtualAddress; + NextBlock = LdrProcessRelocationBlockLongLong(VA, SizeOfBlock, NextOffset, Diff); + + if (!NextBlock) + { + Status = STATUS_INVALID_IMAGE_FORMAT; + goto Exit; + } + } + + Status = STATUS_SUCCESS; +Exit: + return Status; +} + +PIMAGE_BASE_RELOCATION +LdrProcessRelocationBlock( + IN ULONG_PTR VA, + IN ULONG SizeOfBlock, + IN PUSHORT NextOffset, + IN LONG_PTR Diff +) +{ + PIMAGE_BASE_RELOCATION baseRelocation; + + baseRelocation = LdrProcessRelocationBlockLongLong(VA, SizeOfBlock, NextOffset, (LONGLONG)Diff); + + return baseRelocation; +} + +// begin_rebase +PIMAGE_BASE_RELOCATION +LdrProcessRelocationBlockLongLong( + IN ULONG_PTR VA, + IN ULONG SizeOfBlock, + IN PUSHORT NextOffset, + IN LONGLONG Diff +) +{ + PUCHAR FixupVA; + USHORT Offset; + LONG Temp; + //ULONG Temp32; + ULONGLONG Value64; + //LONGLONG Temp64; + + while (SizeOfBlock--) { + + Offset = *NextOffset & (USHORT)0xfff; + FixupVA = (PUCHAR)(VA + Offset); + + // + // Apply the fixups. + // + + switch ((*NextOffset) >> 12) { + + case IMAGE_REL_BASED_HIGHLOW: + // + // HighLow - (32-bits) relocate the high and low half + // of an address. + // + *(LONG UNALIGNED *)FixupVA += (ULONG)Diff; + break; + + case IMAGE_REL_BASED_HIGH: + // + // High - (16-bits) relocate the high half of an address. + // + Temp = *(PUSHORT)FixupVA << 16; + Temp += (ULONG)Diff; + *(PUSHORT)FixupVA = (USHORT)(Temp >> 16); + break; + + case IMAGE_REL_BASED_HIGHADJ: + // + // Adjust high - (16-bits) relocate the high half of an + // address and adjust for sign extension of low half. + // + + // + // If the address has already been relocated then don't + // process it again now or information will be lost. + // + if (Offset & LDRP_RELOCATION_FINAL) { + ++NextOffset; + --SizeOfBlock; + break; + } + + Temp = *(PUSHORT)FixupVA << 16; + ++NextOffset; + --SizeOfBlock; + Temp += (LONG)(*(PSHORT)NextOffset); + Temp += (ULONG)Diff; + Temp += 0x8000; + *(PUSHORT)FixupVA = (USHORT)(Temp >> 16); + + break; + + case IMAGE_REL_BASED_LOW: + // + // Low - (16-bit) relocate the low half of an address. + // + Temp = *(PSHORT)FixupVA; + Temp += (ULONG)Diff; + *(PUSHORT)FixupVA = (USHORT)Temp; + break; + + case IMAGE_REL_BASED_IA64_IMM64: + + // + // Align it to bundle address before fixing up the + // 64-bit immediate value of the movl instruction. + // + + FixupVA = (PUCHAR)((ULONG_PTR)FixupVA & ~(15)); + Value64 = (ULONGLONG)0; + + // + // Extract the lower 32 bits of IMM64 from bundle + // + + /* + EXT_IMM64(Value64, + (PULONG)FixupVA + EMARCH_ENC_I17_IMM7B_INST_WORD_X, + EMARCH_ENC_I17_IMM7B_SIZE_X, + EMARCH_ENC_I17_IMM7B_INST_WORD_POS_X, + EMARCH_ENC_I17_IMM7B_VAL_POS_X); + EXT_IMM64(Value64, + (PULONG)FixupVA + EMARCH_ENC_I17_IMM9D_INST_WORD_X, + EMARCH_ENC_I17_IMM9D_SIZE_X, + EMARCH_ENC_I17_IMM9D_INST_WORD_POS_X, + EMARCH_ENC_I17_IMM9D_VAL_POS_X); + EXT_IMM64(Value64, + (PULONG)FixupVA + EMARCH_ENC_I17_IMM5C_INST_WORD_X, + EMARCH_ENC_I17_IMM5C_SIZE_X, + EMARCH_ENC_I17_IMM5C_INST_WORD_POS_X, + EMARCH_ENC_I17_IMM5C_VAL_POS_X); + EXT_IMM64(Value64, + (PULONG)FixupVA + EMARCH_ENC_I17_IC_INST_WORD_X, + EMARCH_ENC_I17_IC_SIZE_X, + EMARCH_ENC_I17_IC_INST_WORD_POS_X, + EMARCH_ENC_I17_IC_VAL_POS_X); + EXT_IMM64(Value64, + (PULONG)FixupVA + EMARCH_ENC_I17_IMM41a_INST_WORD_X, + EMARCH_ENC_I17_IMM41a_SIZE_X, + EMARCH_ENC_I17_IMM41a_INST_WORD_POS_X, + EMARCH_ENC_I17_IMM41a_VAL_POS_X); + + EXT_IMM64(Value64, + ((PULONG)FixupVA + EMARCH_ENC_I17_IMM41b_INST_WORD_X), + EMARCH_ENC_I17_IMM41b_SIZE_X, + EMARCH_ENC_I17_IMM41b_INST_WORD_POS_X, + EMARCH_ENC_I17_IMM41b_VAL_POS_X); + EXT_IMM64(Value64, + ((PULONG)FixupVA + EMARCH_ENC_I17_IMM41c_INST_WORD_X), + EMARCH_ENC_I17_IMM41c_SIZE_X, + EMARCH_ENC_I17_IMM41c_INST_WORD_POS_X, + EMARCH_ENC_I17_IMM41c_VAL_POS_X); + EXT_IMM64(Value64, + ((PULONG)FixupVA + EMARCH_ENC_I17_SIGN_INST_WORD_X), + EMARCH_ENC_I17_SIGN_SIZE_X, + EMARCH_ENC_I17_SIGN_INST_WORD_POS_X, + EMARCH_ENC_I17_SIGN_VAL_POS_X); + // + // Update 64-bit address + // + + Value64+=Diff; + + // + // Insert IMM64 into bundle + // + + INS_IMM64(Value64, + ((PULONG)FixupVA + EMARCH_ENC_I17_IMM7B_INST_WORD_X), + EMARCH_ENC_I17_IMM7B_SIZE_X, + EMARCH_ENC_I17_IMM7B_INST_WORD_POS_X, + EMARCH_ENC_I17_IMM7B_VAL_POS_X); + INS_IMM64(Value64, + ((PULONG)FixupVA + EMARCH_ENC_I17_IMM9D_INST_WORD_X), + EMARCH_ENC_I17_IMM9D_SIZE_X, + EMARCH_ENC_I17_IMM9D_INST_WORD_POS_X, + EMARCH_ENC_I17_IMM9D_VAL_POS_X); + INS_IMM64(Value64, + ((PULONG)FixupVA + EMARCH_ENC_I17_IMM5C_INST_WORD_X), + EMARCH_ENC_I17_IMM5C_SIZE_X, + EMARCH_ENC_I17_IMM5C_INST_WORD_POS_X, + EMARCH_ENC_I17_IMM5C_VAL_POS_X); + INS_IMM64(Value64, + ((PULONG)FixupVA + EMARCH_ENC_I17_IC_INST_WORD_X), + EMARCH_ENC_I17_IC_SIZE_X, + EMARCH_ENC_I17_IC_INST_WORD_POS_X, + EMARCH_ENC_I17_IC_VAL_POS_X); + INS_IMM64(Value64, + ((PULONG)FixupVA + EMARCH_ENC_I17_IMM41a_INST_WORD_X), + EMARCH_ENC_I17_IMM41a_SIZE_X, + EMARCH_ENC_I17_IMM41a_INST_WORD_POS_X, + EMARCH_ENC_I17_IMM41a_VAL_POS_X); + INS_IMM64(Value64, + ((PULONG)FixupVA + EMARCH_ENC_I17_IMM41b_INST_WORD_X), + EMARCH_ENC_I17_IMM41b_SIZE_X, + EMARCH_ENC_I17_IMM41b_INST_WORD_POS_X, + EMARCH_ENC_I17_IMM41b_VAL_POS_X); + INS_IMM64(Value64, + ((PULONG)FixupVA + EMARCH_ENC_I17_IMM41c_INST_WORD_X), + EMARCH_ENC_I17_IMM41c_SIZE_X, + EMARCH_ENC_I17_IMM41c_INST_WORD_POS_X, + EMARCH_ENC_I17_IMM41c_VAL_POS_X); + INS_IMM64(Value64, + ((PULONG)FixupVA + EMARCH_ENC_I17_SIGN_INST_WORD_X), + EMARCH_ENC_I17_SIGN_SIZE_X, + EMARCH_ENC_I17_SIGN_INST_WORD_POS_X, + EMARCH_ENC_I17_SIGN_VAL_POS_X); + */ + break; + + case IMAGE_REL_BASED_DIR64: + + *(ULONGLONG UNALIGNED *)FixupVA += Diff; + + break; + + case IMAGE_REL_BASED_MIPS_JMPADDR: + // + // JumpAddress - (32-bits) relocate a MIPS jump address. + // + Temp = (*(PULONG)FixupVA & 0x3ffffff) << 2; + Temp += (ULONG)Diff; + *(PULONG)FixupVA = (*(PULONG)FixupVA & ~0x3ffffff) | + ((Temp >> 2) & 0x3ffffff); + + break; + + case IMAGE_REL_BASED_ABSOLUTE: + // + // Absolute - no fixup required. + // + break; + + case IMAGE_REL_BASED_SECTION: + // + // Section Relative reloc. Ignore for now. + // + break; + + case IMAGE_REL_BASED_REL32: + // + // Relative intrasection. Ignore for now. + // + break; + + default: + // + // Illegal - illegal relocation type. + // + + return (PIMAGE_BASE_RELOCATION)NULL; + } + ++NextOffset; + } + return (PIMAGE_BASE_RELOCATION)NextOffset; +}
\ No newline at end of file diff --git a/PastDSEDriver/Driver.c b/PastDSEDriver/Driver.c new file mode 100644 index 0000000..875cf29 --- /dev/null +++ b/PastDSEDriver/Driver.c @@ -0,0 +1,150 @@ +/****************************************************** +* FILENAME: +* Driver.c +* +* DESCRIPTION: +* Driver utility functions. +* +* Copyright Toni Uhlig 2019. All rights reserved. +* +* AUTHOR: +* Toni Uhlig START DATE : 27 Mar 19 +*/ + +#include "Driver.h" + +#include <ntddk.h> +#include <Ntstrsafe.h> + +DRIVER_INITIALIZE DriverEntry; +#pragma alloc_text(INIT, DriverEntry) +DRIVER_UNLOAD DriverUnload; +DRIVER_DISPATCH IODispatch; +#pragma alloc_test(PAGE, IODispatch); + + +NTSTATUS DriverEntry( + _In_ struct _DRIVER_OBJECT *DriverObject, + _In_ PUNICODE_STRING RegistryPath +) +{ + PEPROCESS Process; + NTSTATUS status; + UNICODE_STRING deviceName, deviceDosName; + PDEVICE_OBJECT deviceObject = NULL; + + UNREFERENCED_PARAMETER(RegistryPath); + + status = CheckVersion(); + if (!NT_SUCCESS(status)) + return status; + + KDBG("Initializing ..\n"); + KDBG("System range start: %p\n", MmSystemRangeStart); + KDBG("Code mapped at....: %p\n", DriverEntry); + KDBG("DriverObject......: %p\n", DriverObject); + + Process = PsGetCurrentProcess(); + KDBG("Process...........: %lu (%p)\n", PsGetCurrentProcessId(), Process); + + status = BBInitLdrData((PKLDR_DATA_TABLE_ENTRY)DriverObject->DriverSection); + if (!NT_SUCCESS(status)) + return status; + + DriverObject->MajorFunction[IRP_MJ_CREATE] = + DriverObject->MajorFunction[IRP_MJ_CLOSE] = + DriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL] = IODispatch; + DriverObject->DriverUnload = DriverUnload; + + RtlUnicodeStringInit(&deviceName, DEVICE_NAME); + RtlUnicodeStringInit(&deviceDosName, DEVICE_DOSNAME); + + status = IoCreateDevice(DriverObject, 0, &deviceName, PASTDSE_DEVICE, FILE_DEVICE_UNKNOWN, FALSE, &deviceObject); + if (!NT_SUCCESS(status)) { + KDBG("IoCreateDevice failed with: 0x%X\n", status); + return status; + } + + status = IoCreateSymbolicLink(&deviceDosName, &deviceName); + if (!NT_SUCCESS(status)) { + KDBG("IoCreateSymbolicLink failed with: 0x%X\n", status); + return status; + } + + return STATUS_SUCCESS; +} + +VOID +DriverUnload( + _In_ struct _DRIVER_OBJECT *DriverObject +) +{ + UNICODE_STRING deviceDosName; + + KDBG("Unloading KMDF ManualDriverMapper with DriverObject: %p\n", DriverObject); + + RtlInitUnicodeString(&deviceDosName, DEVICE_DOSNAME); + IoDeleteSymbolicLink(&deviceDosName); + + IoDeleteDevice(DriverObject->DeviceObject); +} + +NTSTATUS IODispatch( + _Inout_ struct _DEVICE_OBJECT *DeviceObject, + _Inout_ struct _IRP *Irp +) +{ + NTSTATUS status = STATUS_SUCCESS; + PIO_STACK_LOCATION irpStack; + PVOID ioBuffer; + ULONG inputBufferLength; + ULONG outputBufferLength; + ULONG ioControlCode = 0; + + UNREFERENCED_PARAMETER(DeviceObject); + + Irp->IoStatus.Status = STATUS_SUCCESS; + Irp->IoStatus.Information = 0; + + irpStack = IoGetCurrentIrpStackLocation(Irp); + ioBuffer = Irp->AssociatedIrp.SystemBuffer; + inputBufferLength = irpStack->Parameters.DeviceIoControl.InputBufferLength; + outputBufferLength = irpStack->Parameters.DeviceIoControl.OutputBufferLength; + + KDBG("DriverDispatch....: %u\n", irpStack->MajorFunction); + switch (irpStack->MajorFunction) { + case IRP_MJ_DEVICE_CONTROL: + { + ioControlCode = irpStack->Parameters.DeviceIoControl.IoControlCode; + KDBG("Dispatch CtrlCode.: 0x%X\n", ioControlCode); + + switch (ioControlCode) { + case IOCTL_PASTDSE_MMAP_DRIVER: + if (inputBufferLength == sizeof(MMAP_DRIVER_INFO) && ioBuffer) { + KDBG("MMAP driver size..: %lu\n", inputBufferLength); + MMAP_DRIVER_INFO *pMmapDrvInf = (MMAP_DRIVER_INFO *)ioBuffer; + wchar_t buf[sizeof(pMmapDrvInf->path)]; + UNICODE_STRING ustrPath; + + RtlCopyMemory(buf, pMmapDrvInf->path, sizeof(pMmapDrvInf->path)); + buf[sizeof(pMmapDrvInf->path) - sizeof(wchar_t)] = L'\0'; + RtlUnicodeStringInit(&ustrPath, buf); + KDBG("MMAP driver path..: %wZ\n", ustrPath); + + Irp->IoStatus.Status = BBMMapDriver(&ustrPath); + } + else Irp->IoStatus.Status = STATUS_INFO_LENGTH_MISMATCH; + break; + default: + KDBG("Unknown device control: 0x%X\n", ioControlCode); + Irp->IoStatus.Status = STATUS_INVALID_PARAMETER; + break; + } + } + } + + status = Irp->IoStatus.Status; + IoCompleteRequest(Irp, IO_NO_INCREMENT); + + return status; +}
\ No newline at end of file diff --git a/PastDSEDriver/Driver.h b/PastDSEDriver/Driver.h new file mode 100644 index 0000000..8eedef7 --- /dev/null +++ b/PastDSEDriver/Driver.h @@ -0,0 +1,154 @@ +/****************************************************** +* FILENAME: +* Driver.h +* +* DESCRIPTION: +* Driver utility functions. +* +* Copyright Toni Uhlig 2019. All rights reserved. +* +* AUTHOR: +* Toni Uhlig START DATE : 27 Mar 19 +*/ + +#pragma once + +#include "PE.h" +#include "Native.h" + +#include <ntddk.h> + +#define PASTDSE L"PastDSE" +#define DEVICE_NAME L"\\Device\\" PASTDSE +#define DEVICE_DOSNAME L"\\DosDevices\\" PASTDSE +#define PASTDSE_DEVICE 0x9C40 +#define MMAPDRV_MAXPATH 512 +#define IOCTL_PASTDSE_MMAP_DRIVER (ULONG)CTL_CODE(PASTDSE_DEVICE, 0x800, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) + +typedef struct MMAP_DRIVER_INFO { + wchar_t path[MMAPDRV_MAXPATH]; +} MMAP_DRIVER_INFO; + + +#ifdef _DEBUG_ +#define KDBG(fmt, ...) DbgPrint("PastDSE: " fmt, __VA_ARGS__) +#else +#define KDBG(fmt, ...) +#endif + +#define PASTDSE_POOL_TAG 'tsaP' + +extern PLIST_ENTRY PsLoadedModuleList; + +NTSTATUS CheckVersion(void); +PVOID GetKernelBase(OUT PULONG pSize); +NTSTATUS RandomMemory32(PVOID buf, SIZE_T siz); + +NTSTATUS BBInitLdrData(IN PKLDR_DATA_TABLE_ENTRY pThisModule); +PVOID BBGetModuleExport(IN PVOID pBase, IN PCCHAR name_ord); +PKLDR_DATA_TABLE_ENTRY BBGetSystemModule(IN PUNICODE_STRING pName, IN PVOID pAddress); +NTSTATUS BBSafeInitString(OUT PUNICODE_STRING result, IN PUNICODE_STRING source); +NTSTATUS BBResolveImageRefs(IN PVOID pImageBase); +NTSTATUS BBCreateCookie(IN PVOID imageBase); +NTSTATUS BBMapWorker(IN PVOID pArg); +NTSTATUS BBMMapDriver(IN PUNICODE_STRING pPath); +NTSTATUS LdrRelocateImage(IN PVOID NewBase); +PIMAGE_BASE_RELOCATION +LdrProcessRelocationBlock( + IN ULONG_PTR VA, + IN ULONG SizeOfBlock, + IN PUSHORT NextOffset, + IN LONG_PTR Diff +); +PIMAGE_BASE_RELOCATION +LdrProcessRelocationBlockLongLong( + IN ULONG_PTR VA, + IN ULONG SizeOfBlock, + IN PUSHORT NextOffset, + IN LONGLONG Diff +); + +typedef struct tagACTCTXW +{ + ULONG cbSize; + ULONG dwFlags; + PWCH lpSource; + USHORT wProcessorArchitecture; + USHORT wLangId; + PWCH lpAssemblyDirectory; + PWCH lpResourceName; + PWCH lpApplicationName; + PVOID hModule; +} ACTCTXW, *PACTCTXW; + +typedef struct tagACTCTXW32 +{ + ULONG cbSize; + ULONG dwFlags; + ULONG lpSource; + USHORT wProcessorArchitecture; + USHORT wLangId; + ULONG lpAssemblyDirectory; + ULONG lpResourceName; + ULONG lpApplicationName; + ULONG hModule; +} ACTCTXW32, *PACTCTXW32; + +typedef enum _MmapFlags +{ + KNoFlags = 0x00, // No flags + KManualImports = 0x01, // Manually map import libraries + KWipeHeader = 0x04, // Wipe image PE headers + KHideVAD = 0x10, // Make image appear as PAGE_NOACESS region + KRebaseProcess = 0x40, // If target image is an .exe file, process base address will be replaced with mapped module value + + KNoExceptions = 0x01000, // Do not create custom exception handler + KNoSxS = 0x08000, // Do not apply SxS activation context + KNoTLS = 0x10000, // Skip TLS initialization and don't execute TLS callbacks +} KMmapFlags; + +typedef struct _USER_CONTEXT +{ + UCHAR code[0x1000]; // Code buffer + union + { + UNICODE_STRING ustr; + UNICODE_STRING32 ustr32; + }; + wchar_t buffer[0x400]; // Buffer for unicode string + + + // Activation context data + union + { + ACTCTXW actx; + ACTCTXW32 actx32; + }; + HANDLE hCTX; + ULONG hCookie; + + PVOID ptr; // Tmp data + union + { + NTSTATUS status; // Last execution status + PVOID retVal; // Function return value + ULONG retVal32; // Function return value + }; + + //UCHAR tlsBuf[0x100]; +} USER_CONTEXT, *PUSER_CONTEXT; + +typedef struct _MMAP_CONTEXT +{ + PEPROCESS pProcess; // Target process + PVOID pWorkerBuf; // Worker thread code buffer + HANDLE hWorker; // Worker thread handle + PETHREAD pWorker; // Worker thread object + LIST_ENTRY modules; // Manual module list + PUSER_CONTEXT userMem; // Tmp buffer in user space + HANDLE hSync; // APC sync handle + PKEVENT pSync; // APC sync object + PVOID pSetEvent; // ZwSetEvent address + PVOID pLoadImage; // LdrLoadDll address + BOOLEAN tlsInitialized; // Static TLS was initialized +} MMAP_CONTEXT, *PMMAP_CONTEXT;
\ No newline at end of file diff --git a/PastDSEDriver/Imports.h b/PastDSEDriver/Imports.h new file mode 100644 index 0000000..7e9db07 --- /dev/null +++ b/PastDSEDriver/Imports.h @@ -0,0 +1,58 @@ +/****************************************************** +* FILENAME: +* Imports.h +* +* DESCRIPTION: +* Driver utility functions. +* +* Copyright Toni Uhlig 2019. All rights reserved. +* +* AUTHOR: +* DarthTon +* Toni Uhlig START DATE : 27 Mar 19 +*/ + +#pragma once + +#include "Native.h" + +#include <ntddk.h> + +NTSYSAPI NTSTATUS NTAPI +ZwQueryInformationThread( + IN HANDLE ThreadHandle, + IN THREADINFOCLASS ThreadInformationClass, + OUT PVOID ThreadInformation, + IN ULONG ThreadInformationLength, + OUT PULONG ReturnLength OPTIONAL +); + +NTSYSAPI NTSTATUS NTAPI +ZwQuerySystemInformation( + IN SYSTEM_INFORMATION_CLASS SystemInformationClass, + OUT PVOID SystemInformation, + IN ULONG SystemInformationLength, + OUT PULONG ReturnLength OPTIONAL +); + +NTSYSAPI +PIMAGE_NT_HEADERS +NTAPI +RtlImageNtHeader(PVOID Base); + +NTSYSAPI +PVOID +NTAPI +RtlImageDirectoryEntryToData( + PVOID ImageBase, + BOOLEAN MappedAsImage, + USHORT DirectoryEntry, + PULONG Size +); + +NTSYSAPI +ULONG +NTAPI +RtlRandomEx( + _Inout_ PULONG Seed +);
\ No newline at end of file diff --git a/PastDSEDriver/Native.h b/PastDSEDriver/Native.h new file mode 100644 index 0000000..14a201a --- /dev/null +++ b/PastDSEDriver/Native.h @@ -0,0 +1,242 @@ +/****************************************************** +* FILENAME: +* Native.h +* +* DESCRIPTION: +* Driver utility functions. +* +* Copyright Toni Uhlig 2019. All rights reserved. +* +* AUTHOR: +* DarthTon +* Toni Uhlig START DATE : 27 Mar 19 +*/ + +#pragma once + +typedef struct _THREAD_BASIC_INFORMATION +{ + NTSTATUS ExitStatus; + PVOID TebBaseAddress; + CLIENT_ID ClientId; + ULONG_PTR AffinityMask; + LONG Priority; + LONG BasePriority; +} THREAD_BASIC_INFORMATION, *PTHREAD_BASIC_INFORMATION; + +typedef struct _NON_PAGED_DEBUG_INFO +{ + USHORT Signature; + USHORT Flags; + ULONG Size; + USHORT Machine; + USHORT Characteristics; + ULONG TimeDateStamp; + ULONG CheckSum; + ULONG SizeOfImage; + ULONGLONG ImageBase; +} NON_PAGED_DEBUG_INFO, *PNON_PAGED_DEBUG_INFO; + +typedef struct _KLDR_DATA_TABLE_ENTRY +{ + LIST_ENTRY InLoadOrderLinks; + PVOID ExceptionTable; + ULONG ExceptionTableSize; + // ULONG padding on IA64 + PVOID GpValue; + PNON_PAGED_DEBUG_INFO NonPagedDebugInfo; + PVOID DllBase; + PVOID EntryPoint; + ULONG SizeOfImage; + UNICODE_STRING FullDllName; + UNICODE_STRING BaseDllName; + ULONG Flags; + USHORT LoadCount; + USHORT __Unused5; + PVOID SectionPointer; + ULONG CheckSum; + // ULONG padding on IA64 + PVOID LoadedImports; + PVOID PatchInformation; +} KLDR_DATA_TABLE_ENTRY, *PKLDR_DATA_TABLE_ENTRY; + +typedef struct _RTL_PROCESS_MODULE_INFORMATION +{ + HANDLE Section; // Not filled in + PVOID MappedBase; + PVOID ImageBase; + ULONG ImageSize; + ULONG Flags; + USHORT LoadOrderIndex; + USHORT InitOrderIndex; + USHORT LoadCount; + USHORT OffsetToFileName; + UCHAR FullPathName[MAXIMUM_FILENAME_LENGTH]; +} RTL_PROCESS_MODULE_INFORMATION, *PRTL_PROCESS_MODULE_INFORMATION; + +typedef struct _RTL_PROCESS_MODULES +{ + ULONG NumberOfModules; + RTL_PROCESS_MODULE_INFORMATION Modules[1]; +} RTL_PROCESS_MODULES, *PRTL_PROCESS_MODULES; + +typedef enum _SYSTEM_INFORMATION_CLASS +{ + SystemBasicInformation = 0x0, + SystemProcessorInformation = 0x1, + SystemPerformanceInformation = 0x2, + SystemTimeOfDayInformation = 0x3, + SystemPathInformation = 0x4, + SystemProcessInformation = 0x5, + SystemCallCountInformation = 0x6, + SystemDeviceInformation = 0x7, + SystemProcessorPerformanceInformation = 0x8, + SystemFlagsInformation = 0x9, + SystemCallTimeInformation = 0xa, + SystemModuleInformation = 0xb, + SystemLocksInformation = 0xc, + SystemStackTraceInformation = 0xd, + SystemPagedPoolInformation = 0xe, + SystemNonPagedPoolInformation = 0xf, + SystemHandleInformation = 0x10, + SystemObjectInformation = 0x11, + SystemPageFileInformation = 0x12, + SystemVdmInstemulInformation = 0x13, + SystemVdmBopInformation = 0x14, + SystemFileCacheInformation = 0x15, + SystemPoolTagInformation = 0x16, + SystemInterruptInformation = 0x17, + SystemDpcBehaviorInformation = 0x18, + SystemFullMemoryInformation = 0x19, + SystemLoadGdiDriverInformation = 0x1a, + SystemUnloadGdiDriverInformation = 0x1b, + SystemTimeAdjustmentInformation = 0x1c, + SystemSummaryMemoryInformation = 0x1d, + SystemMirrorMemoryInformation = 0x1e, + SystemPerformanceTraceInformation = 0x1f, + SystemObsolete0 = 0x20, + SystemExceptionInformation = 0x21, + SystemCrashDumpStateInformation = 0x22, + SystemKernelDebuggerInformation = 0x23, + SystemContextSwitchInformation = 0x24, + SystemRegistryQuotaInformation = 0x25, + SystemExtendServiceTableInformation = 0x26, + SystemPrioritySeperation = 0x27, + SystemVerifierAddDriverInformation = 0x28, + SystemVerifierRemoveDriverInformation = 0x29, + SystemProcessorIdleInformation = 0x2a, + SystemLegacyDriverInformation = 0x2b, + SystemCurrentTimeZoneInformation = 0x2c, + SystemLookasideInformation = 0x2d, + SystemTimeSlipNotification = 0x2e, + SystemSessionCreate = 0x2f, + SystemSessionDetach = 0x30, + SystemSessionInformation = 0x31, + SystemRangeStartInformation = 0x32, + SystemVerifierInformation = 0x33, + SystemVerifierThunkExtend = 0x34, + SystemSessionProcessInformation = 0x35, + SystemLoadGdiDriverInSystemSpace = 0x36, + SystemNumaProcessorMap = 0x37, + SystemPrefetcherInformation = 0x38, + SystemExtendedProcessInformation = 0x39, + SystemRecommendedSharedDataAlignment = 0x3a, + SystemComPlusPackage = 0x3b, + SystemNumaAvailableMemory = 0x3c, + SystemProcessorPowerInformation = 0x3d, + SystemEmulationBasicInformation = 0x3e, + SystemEmulationProcessorInformation = 0x3f, + SystemExtendedHandleInformation = 0x40, + SystemLostDelayedWriteInformation = 0x41, + SystemBigPoolInformation = 0x42, + SystemSessionPoolTagInformation = 0x43, + SystemSessionMappedViewInformation = 0x44, + SystemHotpatchInformation = 0x45, + SystemObjectSecurityMode = 0x46, + SystemWatchdogTimerHandler = 0x47, + SystemWatchdogTimerInformation = 0x48, + SystemLogicalProcessorInformation = 0x49, + SystemWow64SharedInformationObsolete = 0x4a, + SystemRegisterFirmwareTableInformationHandler = 0x4b, + SystemFirmwareTableInformation = 0x4c, + SystemModuleInformationEx = 0x4d, + SystemVerifierTriageInformation = 0x4e, + SystemSuperfetchInformation = 0x4f, + SystemMemoryListInformation = 0x50, + SystemFileCacheInformationEx = 0x51, + SystemThreadPriorityClientIdInformation = 0x52, + SystemProcessorIdleCycleTimeInformation = 0x53, + SystemVerifierCancellationInformation = 0x54, + SystemProcessorPowerInformationEx = 0x55, + SystemRefTraceInformation = 0x56, + SystemSpecialPoolInformation = 0x57, + SystemProcessIdInformation = 0x58, + SystemErrorPortInformation = 0x59, + SystemBootEnvironmentInformation = 0x5a, + SystemHypervisorInformation = 0x5b, + SystemVerifierInformationEx = 0x5c, + SystemTimeZoneInformation = 0x5d, + SystemImageFileExecutionOptionsInformation = 0x5e, + SystemCoverageInformation = 0x5f, + SystemPrefetchPatchInformation = 0x60, + SystemVerifierFaultsInformation = 0x61, + SystemSystemPartitionInformation = 0x62, + SystemSystemDiskInformation = 0x63, + SystemProcessorPerformanceDistribution = 0x64, + SystemNumaProximityNodeInformation = 0x65, + SystemDynamicTimeZoneInformation = 0x66, + SystemCodeIntegrityInformation = 0x67, + SystemProcessorMicrocodeUpdateInformation = 0x68, + SystemProcessorBrandString = 0x69, + SystemVirtualAddressInformation = 0x6a, + SystemLogicalProcessorAndGroupInformation = 0x6b, + SystemProcessorCycleTimeInformation = 0x6c, + SystemStoreInformation = 0x6d, + SystemRegistryAppendString = 0x6e, + SystemAitSamplingValue = 0x6f, + SystemVhdBootInformation = 0x70, + SystemCpuQuotaInformation = 0x71, + SystemNativeBasicInformation = 0x72, + SystemErrorPortTimeouts = 0x73, + SystemLowPriorityIoInformation = 0x74, + SystemBootEntropyInformation = 0x75, + SystemVerifierCountersInformation = 0x76, + SystemPagedPoolInformationEx = 0x77, + SystemSystemPtesInformationEx = 0x78, + SystemNodeDistanceInformation = 0x79, + SystemAcpiAuditInformation = 0x7a, + SystemBasicPerformanceInformation = 0x7b, + SystemQueryPerformanceCounterInformation = 0x7c, + SystemSessionBigPoolInformation = 0x7d, + SystemBootGraphicsInformation = 0x7e, + SystemScrubPhysicalMemoryInformation = 0x7f, + SystemBadPageInformation = 0x80, + SystemProcessorProfileControlArea = 0x81, + SystemCombinePhysicalMemoryInformation = 0x82, + SystemEntropyInterruptTimingInformation = 0x83, + SystemConsoleInformation = 0x84, + SystemPlatformBinaryInformation = 0x85, + SystemThrottleNotificationInformation = 0x86, + SystemHypervisorProcessorCountInformation = 0x87, + SystemDeviceDataInformation = 0x88, + SystemDeviceDataEnumerationInformation = 0x89, + SystemMemoryTopologyInformation = 0x8a, + SystemMemoryChannelInformation = 0x8b, + SystemBootLogoInformation = 0x8c, + SystemProcessorPerformanceInformationEx = 0x8d, + SystemSpare0 = 0x8e, + SystemSecureBootPolicyInformation = 0x8f, + SystemPageFileInformationEx = 0x90, + SystemSecureBootInformation = 0x91, + SystemEntropyInterruptTimingRawInformation = 0x92, + SystemPortableWorkspaceEfiLauncherInformation = 0x93, + SystemFullProcessInformation = 0x94, + SystemKernelDebuggerInformationEx = 0x95, + SystemBootMetadataInformation = 0x96, + SystemSoftRebootInformation = 0x97, + SystemElamCertificateInformation = 0x98, + SystemOfflineDumpConfigInformation = 0x99, + SystemProcessorFeaturesInformation = 0x9a, + SystemRegistryReconciliationInformation = 0x9b, + MaxSystemInfoClass = 0x9c, +} SYSTEM_INFORMATION_CLASS;
\ No newline at end of file diff --git a/PastDSEDriver/PE.h b/PastDSEDriver/PE.h new file mode 100644 index 0000000..d7dec91 --- /dev/null +++ b/PastDSEDriver/PE.h @@ -0,0 +1,293 @@ +/****************************************************** +* FILENAME: +* PE.h +* +* DESCRIPTION: +* Driver utility functions. +* +* Copyright Toni Uhlig 2019. All rights reserved. +* +* AUTHOR: +* DarthTon +* Toni Uhlig START DATE : 27 Mar 19 +*/ + +#pragma once + +#include <ntddk.h> + + +#define IMAGE_DOS_SIGNATURE 0x5A4D // MZ +#define IMAGE_NT_SIGNATURE 0x00004550 // PE00 + +#define IMAGE_NT_OPTIONAL_HDR64_MAGIC 0x20b +#define IMAGE_NUMBEROF_DIRECTORY_ENTRIES 16 + +#define IMAGE_DIRECTORY_ENTRY_EXPORT 0 // Export Directory +#define IMAGE_DIRECTORY_ENTRY_IMPORT 1 // Import Directory +#define IMAGE_DIRECTORY_ENTRY_RESOURCE 2 // Resource Directory +#define IMAGE_DIRECTORY_ENTRY_EXCEPTION 3 // Exception Directory +#define IMAGE_DIRECTORY_ENTRY_SECURITY 4 // Security Directory +#define IMAGE_DIRECTORY_ENTRY_BASERELOC 5 // Base Relocation Table +#define IMAGE_DIRECTORY_ENTRY_DEBUG 6 // Debug Directory +#define IMAGE_DIRECTORY_ENTRY_ARCHITECTURE 7 // Architecture Specific Data +#define IMAGE_DIRECTORY_ENTRY_GLOBALPTR 8 // RVA of GP +#define IMAGE_DIRECTORY_ENTRY_TLS 9 // TLS Directory +#define IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG 10 // Load Configuration Directory +#define IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT 11 // Bound Import Directory in headers +#define IMAGE_DIRECTORY_ENTRY_IAT 12 // Import Address Table +#define IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT 13 // Delay Load Import Descriptors +#define IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR 14 // COM Runtime descriptor + +#define IMAGE_REL_BASED_ABSOLUTE 0 +#define IMAGE_REL_BASED_HIGH 1 +#define IMAGE_REL_BASED_LOW 2 +#define IMAGE_REL_BASED_HIGHLOW 3 +#define IMAGE_REL_BASED_HIGHADJ 4 +#define IMAGE_REL_BASED_MIPS_JMPADDR 5 +#define IMAGE_REL_BASED_SECTION 6 +#define IMAGE_REL_BASED_REL32 7 +#define IMAGE_REL_BASED_MIPS_JMPADDR16 9 +#define IMAGE_REL_BASED_IA64_IMM64 9 +#define IMAGE_REL_BASED_DIR64 10 + +#define IMAGE_SIZEOF_BASE_RELOCATION 8 + + +#define IMAGE_FILE_RELOCS_STRIPPED 0x0001 // Relocation info stripped from file. +#define IMAGE_FILE_EXECUTABLE_IMAGE 0x0002 // File is executable (i.e. no unresolved external references). +#define IMAGE_FILE_LINE_NUMS_STRIPPED 0x0004 // Line nunbers stripped from file. +#define IMAGE_FILE_LOCAL_SYMS_STRIPPED 0x0008 // Local symbols stripped from file. +#define IMAGE_FILE_AGGRESIVE_WS_TRIM 0x0010 // Aggressively trim working set +#define IMAGE_FILE_LARGE_ADDRESS_AWARE 0x0020 // App can handle >2gb addresses +#define IMAGE_FILE_BYTES_REVERSED_LO 0x0080 // Bytes of machine word are reversed. +#define IMAGE_FILE_32BIT_MACHINE 0x0100 // 32 bit word machine. +#define IMAGE_FILE_DEBUG_STRIPPED 0x0200 // Debugging info stripped from file in .DBG file +#define IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP 0x0400 // If Image is on removable media, copy and run from the swap file. +#define IMAGE_FILE_NET_RUN_FROM_SWAP 0x0800 // If Image is on Net, copy and run from the swap file. +#define IMAGE_FILE_SYSTEM 0x1000 // System File. +#define IMAGE_FILE_DLL 0x2000 // File is a DLL. +#define IMAGE_FILE_UP_SYSTEM_ONLY 0x4000 // File should only be run on a UP machine +#define IMAGE_FILE_BYTES_REVERSED_HI 0x8000 // Bytes of machine word are reversed. + +#define IMAGE_FILE_MACHINE_UNKNOWN 0 +#define IMAGE_FILE_MACHINE_I386 0x014c // Intel 386. +#define IMAGE_FILE_MACHINE_R3000 0x0162 // MIPS little-endian, 0x160 big-endian +#define IMAGE_FILE_MACHINE_R4000 0x0166 // MIPS little-endian +#define IMAGE_FILE_MACHINE_R10000 0x0168 // MIPS little-endian +#define IMAGE_FILE_MACHINE_WCEMIPSV2 0x0169 // MIPS little-endian WCE v2 +#define IMAGE_FILE_MACHINE_ALPHA 0x0184 // Alpha_AXP +#define IMAGE_FILE_MACHINE_SH3 0x01a2 // SH3 little-endian +#define IMAGE_FILE_MACHINE_SH3DSP 0x01a3 +#define IMAGE_FILE_MACHINE_SH3E 0x01a4 // SH3E little-endian +#define IMAGE_FILE_MACHINE_SH4 0x01a6 // SH4 little-endian +#define IMAGE_FILE_MACHINE_SH5 0x01a8 // SH5 +#define IMAGE_FILE_MACHINE_ARM 0x01c0 // ARM Little-Endian +#define IMAGE_FILE_MACHINE_THUMB 0x01c2 // ARM Thumb/Thumb-2 Little-Endian +#define IMAGE_FILE_MACHINE_ARMNT 0x01c4 // ARM Thumb-2 Little-Endian +#define IMAGE_FILE_MACHINE_AM33 0x01d3 +#define IMAGE_FILE_MACHINE_POWERPC 0x01F0 // IBM PowerPC Little-Endian +#define IMAGE_FILE_MACHINE_POWERPCFP 0x01f1 +#define IMAGE_FILE_MACHINE_IA64 0x0200 // Intel 64 +#define IMAGE_FILE_MACHINE_MIPS16 0x0266 // MIPS +#define IMAGE_FILE_MACHINE_ALPHA64 0x0284 // ALPHA64 +#define IMAGE_FILE_MACHINE_MIPSFPU 0x0366 // MIPS +#define IMAGE_FILE_MACHINE_MIPSFPU16 0x0466 // MIPS +#define IMAGE_FILE_MACHINE_AXP64 IMAGE_FILE_MACHINE_ALPHA64 +#define IMAGE_FILE_MACHINE_TRICORE 0x0520 // Infineon +#define IMAGE_FILE_MACHINE_CEF 0x0CEF +#define IMAGE_FILE_MACHINE_EBC 0x0EBC // EFI Byte Code +#define IMAGE_FILE_MACHINE_AMD64 0x8664 // AMD64 (K8) +#define IMAGE_FILE_MACHINE_M32R 0x9041 // M32R little-endian +#define IMAGE_FILE_MACHINE_CEE 0xC0EE + +#define IMAGE_ORDINAL_FLAG64 0x8000000000000000 + +#define CFG_DIR_VAL_T(hdr, dir, val) ((PIMAGE_LOAD_CONFIG_DIRECTORY64)dir)->val +#define THUNK_VAL_T(hdr, ptr, val) ((PIMAGE_THUNK_DATA64)ptr)->val + +typedef struct _IMAGE_DOS_HEADER +{ + USHORT e_magic; + USHORT e_cblp; + USHORT e_cp; + USHORT e_crlc; + USHORT e_cparhdr; + USHORT e_minalloc; + USHORT e_maxalloc; + USHORT e_ss; + USHORT e_sp; + USHORT e_csum; + USHORT e_ip; + USHORT e_cs; + USHORT e_lfarlc; + USHORT e_ovno; + USHORT e_res[4]; + USHORT e_oemid; + USHORT e_oeminfo; + USHORT e_res2[10]; + LONG e_lfanew; +} IMAGE_DOS_HEADER, *PIMAGE_DOS_HEADER; + +typedef struct _IMAGE_SECTION_HEADER +{ + UCHAR Name[8]; + union + { + ULONG PhysicalAddress; + ULONG VirtualSize; + } Misc; + ULONG VirtualAddress; + ULONG SizeOfRawData; + ULONG PointerToRawData; + ULONG PointerToRelocations; + ULONG PointerToLinenumbers; + USHORT NumberOfRelocations; + USHORT NumberOfLinenumbers; + ULONG Characteristics; +} IMAGE_SECTION_HEADER, *PIMAGE_SECTION_HEADER; + +typedef struct _IMAGE_FILE_HEADER // Size=20 +{ + USHORT Machine; + USHORT NumberOfSections; + ULONG TimeDateStamp; + ULONG PointerToSymbolTable; + ULONG NumberOfSymbols; + USHORT SizeOfOptionalHeader; + USHORT Characteristics; +} IMAGE_FILE_HEADER, *PIMAGE_FILE_HEADER; + +typedef struct _IMAGE_DATA_DIRECTORY +{ + ULONG VirtualAddress; + ULONG Size; +} IMAGE_DATA_DIRECTORY, *PIMAGE_DATA_DIRECTORY; + +typedef struct _IMAGE_OPTIONAL_HEADER64 +{ + USHORT Magic; + UCHAR MajorLinkerVersion; + UCHAR MinorLinkerVersion; + ULONG SizeOfCode; + ULONG SizeOfInitializedData; + ULONG SizeOfUninitializedData; + ULONG AddressOfEntryPoint; + ULONG BaseOfCode; + ULONGLONG ImageBase; + ULONG SectionAlignment; + ULONG FileAlignment; + USHORT MajorOperatingSystemVersion; + USHORT MinorOperatingSystemVersion; + USHORT MajorImageVersion; + USHORT MinorImageVersion; + USHORT MajorSubsystemVersion; + USHORT MinorSubsystemVersion; + ULONG Win32VersionValue; + ULONG SizeOfImage; + ULONG SizeOfHeaders; + ULONG CheckSum; + USHORT Subsystem; + USHORT DllCharacteristics; + ULONGLONG SizeOfStackReserve; + ULONGLONG SizeOfStackCommit; + ULONGLONG SizeOfHeapReserve; + ULONGLONG SizeOfHeapCommit; + ULONG LoaderFlags; + ULONG NumberOfRvaAndSizes; + struct _IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES]; +} IMAGE_OPTIONAL_HEADER64, *PIMAGE_OPTIONAL_HEADER64; + +typedef struct _IMAGE_NT_HEADERS64 +{ + ULONG Signature; + struct _IMAGE_FILE_HEADER FileHeader; + struct _IMAGE_OPTIONAL_HEADER64 OptionalHeader; +} IMAGE_NT_HEADERS64, *PIMAGE_NT_HEADERS64; + +typedef struct _IMAGE_EXPORT_DIRECTORY { + ULONG Characteristics; + ULONG TimeDateStamp; + USHORT MajorVersion; + USHORT MinorVersion; + ULONG Name; + ULONG Base; + ULONG NumberOfFunctions; + ULONG NumberOfNames; + ULONG AddressOfFunctions; // RVA from base of image + ULONG AddressOfNames; // RVA from base of image + ULONG AddressOfNameOrdinals; // RVA from base of image +} IMAGE_EXPORT_DIRECTORY, *PIMAGE_EXPORT_DIRECTORY; + +typedef struct _IMAGE_BASE_RELOCATION { + ULONG VirtualAddress; + ULONG SizeOfBlock; +} IMAGE_BASE_RELOCATION; +typedef IMAGE_BASE_RELOCATION UNALIGNED * PIMAGE_BASE_RELOCATION; + +typedef struct _IMAGE_IMPORT_BY_NAME { + USHORT Hint; + CHAR Name[1]; +} IMAGE_IMPORT_BY_NAME, *PIMAGE_IMPORT_BY_NAME; + + +// warning C4201: nonstandard extension used : nameless struct/union +#pragma warning (disable : 4201) + +typedef struct _IMAGE_IMPORT_DESCRIPTOR +{ + union { + ULONG Characteristics; // 0 for terminating null import descriptor + ULONG OriginalFirstThunk; // RVA to original unbound IAT (PIMAGE_THUNK_DATA) + }; + ULONG TimeDateStamp; // 0 if not bound, + // -1 if bound, and real date\time stamp + // in IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT (new BIND) + // O.W. date/time stamp of DLL bound to (Old BIND) + + ULONG ForwarderChain; // -1 if no forwarders + ULONG Name; + ULONG FirstThunk; // RVA to IAT (if bound this IAT has actual addresses) +} IMAGE_IMPORT_DESCRIPTOR; +typedef IMAGE_IMPORT_DESCRIPTOR UNALIGNED *PIMAGE_IMPORT_DESCRIPTOR; + + +typedef struct _IMAGE_THUNK_DATA64 +{ + union + { + ULONGLONG ForwarderString; // PBYTE + ULONGLONG Function; // PULONG + ULONGLONG Ordinal; + ULONGLONG AddressOfData; // PIMAGE_IMPORT_BY_NAME + } u1; +} IMAGE_THUNK_DATA64; +typedef IMAGE_THUNK_DATA64 * PIMAGE_THUNK_DATA64; + +typedef struct _IMAGE_LOAD_CONFIG_DIRECTORY64 { + ULONG Size; + ULONG TimeDateStamp; + USHORT MajorVersion; + USHORT MinorVersion; + ULONG GlobalFlagsClear; + ULONG GlobalFlagsSet; + ULONG CriticalSectionDefaultTimeout; + ULONGLONG DeCommitFreeBlockThreshold; + ULONGLONG DeCommitTotalFreeThreshold; + ULONGLONG LockPrefixTable; // VA + ULONGLONG MaximumAllocationSize; + ULONGLONG VirtualMemoryThreshold; + ULONGLONG ProcessAffinityMask; + ULONG ProcessHeapFlags; + USHORT CSDVersion; + USHORT Reserved1; + ULONGLONG EditList; // VA + ULONGLONG SecurityCookie; // VA + ULONGLONG SEHandlerTable; // VA + ULONGLONG SEHandlerCount; + ULONGLONG GuardCFCheckFunctionPointer; // VA + ULONGLONG Reserved2; + ULONGLONG GuardCFFunctionTable; // VA + ULONGLONG GuardCFFunctionCount; + ULONG GuardFlags; +} IMAGE_LOAD_CONFIG_DIRECTORY64, *PIMAGE_LOAD_CONFIG_DIRECTORY64;
\ No newline at end of file diff --git a/PastDSEDriver/PastDSEDriver.vcxproj b/PastDSEDriver/PastDSEDriver.vcxproj new file mode 100644 index 0000000..8a9b5c5 --- /dev/null +++ b/PastDSEDriver/PastDSEDriver.vcxproj @@ -0,0 +1,125 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <ItemGroup Label="ProjectConfigurations"> + <ProjectConfiguration Include="Debug|Win32"> + <Configuration>Debug</Configuration> + <Platform>Win32</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Release|Win32"> + <Configuration>Release</Configuration> + <Platform>Win32</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Debug|x64"> + <Configuration>Debug</Configuration> + <Platform>x64</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Release|x64"> + <Configuration>Release</Configuration> + <Platform>x64</Platform> + </ProjectConfiguration> + </ItemGroup> + <PropertyGroup Label="Globals"> + <ProjectGuid>{3B50D1AD-DF51-4459-9BDE-E04202A2EFAE}</ProjectGuid> + <TemplateGuid>{1bc93793-694f-48fe-9372-81e2b05556fd}</TemplateGuid> + <TargetFrameworkVersion>v4.5</TargetFrameworkVersion> + <MinimumVisualStudioVersion>12.0</MinimumVisualStudioVersion> + <Configuration>Debug</Configuration> + <Platform Condition="'$(Platform)' == ''">Win32</Platform> + <RootNamespace>PastDSE</RootNamespace> + <ProjectName>PastDSEDriver</ProjectName> + </PropertyGroup> + <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" /> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> + <TargetVersion>Windows10</TargetVersion> + <UseDebugLibraries>true</UseDebugLibraries> + <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset> + <ConfigurationType>Driver</ConfigurationType> + <DriverType>KMDF</DriverType> + <DriverTargetPlatform>Universal</DriverTargetPlatform> + <SpectreMitigation>false</SpectreMitigation> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration"> + <TargetVersion>Windows10</TargetVersion> + <UseDebugLibraries>false</UseDebugLibraries> + <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset> + <ConfigurationType>Driver</ConfigurationType> + <DriverType>KMDF</DriverType> + <DriverTargetPlatform>Universal</DriverTargetPlatform> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration"> + <TargetVersion>Windows10</TargetVersion> + <UseDebugLibraries>true</UseDebugLibraries> + <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset> + <ConfigurationType>Driver</ConfigurationType> + <DriverType>KMDF</DriverType> + <DriverTargetPlatform>Universal</DriverTargetPlatform> + <SpectreMitigation>false</SpectreMitigation> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration"> + <TargetVersion>Windows10</TargetVersion> + <UseDebugLibraries>false</UseDebugLibraries> + <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset> + <ConfigurationType>Driver</ConfigurationType> + <DriverType>KMDF</DriverType> + <DriverTargetPlatform>Universal</DriverTargetPlatform> + <SpectreMitigation>false</SpectreMitigation> + </PropertyGroup> + <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" /> + <ImportGroup Label="ExtensionSettings"> + </ImportGroup> + <ImportGroup Label="PropertySheets"> + <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> + </ImportGroup> + <PropertyGroup Label="UserMacros" /> + <PropertyGroup /> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> + <DebuggerFlavor>DbgengKernelDebugger</DebuggerFlavor> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> + <DebuggerFlavor>DbgengKernelDebugger</DebuggerFlavor> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> + <DebuggerFlavor>DbgengKernelDebugger</DebuggerFlavor> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> + <DebuggerFlavor>DbgengKernelDebugger</DebuggerFlavor> + </PropertyGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> + <ClCompile> + <PreprocessorDefinitions>_DEBUG_;%(PreprocessorDefinitions)</PreprocessorDefinitions> + <FavorSizeOrSpeed>Size</FavorSizeOrSpeed> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> + <TreatWChar_tAsBuiltInType>false</TreatWChar_tAsBuiltInType> + </ClCompile> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> + <ClCompile> + <PreprocessorDefinitions>_WIN10_;%(PreprocessorDefinitions)</PreprocessorDefinitions> + <FavorSizeOrSpeed>Size</FavorSizeOrSpeed> + </ClCompile> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> + <ClCompile> + <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> + <TreatWChar_tAsBuiltInType>false</TreatWChar_tAsBuiltInType> + </ClCompile> + </ItemDefinitionGroup> + <ItemGroup> + <FilesToPackage Include="$(TargetPath)" /> + </ItemGroup> + <ItemGroup> + <ClCompile Include="BlackBone.c" /> + <ClCompile Include="BlackBoneLoaderReloc.c" /> + <ClCompile Include="Driver.c" /> + <ClCompile Include="Utils.c" /> + </ItemGroup> + <ItemGroup> + <ClInclude Include="Driver.h" /> + <ClInclude Include="Imports.h" /> + <ClInclude Include="Native.h" /> + <ClInclude Include="PE.h" /> + </ItemGroup> + <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" /> + <ImportGroup Label="ExtensionTargets"> + </ImportGroup> +</Project>
\ No newline at end of file diff --git a/PastDSEDriver/PastDSEDriver.vcxproj.filters b/PastDSEDriver/PastDSEDriver.vcxproj.filters new file mode 100644 index 0000000..5d55943 --- /dev/null +++ b/PastDSEDriver/PastDSEDriver.vcxproj.filters @@ -0,0 +1,43 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <ItemGroup> + <Filter Include="Header Files"> + <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier> + <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions> + </Filter> + <Filter Include="Core"> + <UniqueIdentifier>{aa4314ac-1a30-4c39-b31d-725fa2da7e1c}</UniqueIdentifier> + </Filter> + <Filter Include="Header Files\Internal"> + <UniqueIdentifier>{d265113c-3f2e-4f6e-af04-c7d655e48143}</UniqueIdentifier> + </Filter> + </ItemGroup> + <ItemGroup> + <ClCompile Include="Driver.c"> + <Filter>Core</Filter> + </ClCompile> + <ClCompile Include="Utils.c"> + <Filter>Core</Filter> + </ClCompile> + <ClCompile Include="BlackBone.c"> + <Filter>Core</Filter> + </ClCompile> + <ClCompile Include="BlackBoneLoaderReloc.c"> + <Filter>Core</Filter> + </ClCompile> + </ItemGroup> + <ItemGroup> + <ClInclude Include="Imports.h"> + <Filter>Header Files\Internal</Filter> + </ClInclude> + <ClInclude Include="Driver.h"> + <Filter>Header Files</Filter> + </ClInclude> + <ClInclude Include="PE.h"> + <Filter>Header Files\Internal</Filter> + </ClInclude> + <ClInclude Include="Native.h"> + <Filter>Header Files\Internal</Filter> + </ClInclude> + </ItemGroup> +</Project>
\ No newline at end of file diff --git a/PastDSEDriver/Utils.c b/PastDSEDriver/Utils.c new file mode 100644 index 0000000..866e606 --- /dev/null +++ b/PastDSEDriver/Utils.c @@ -0,0 +1,129 @@ +/****************************************************** +* FILENAME: +* Utils.c +* +* DESCRIPTION: +* Driver utility functions. +* +* Copyright Toni Uhlig 2019. All rights reserved. +* +* AUTHOR: +* Toni Uhlig START DATE : 27 Mar 19 +*/ + +#include "Driver.h" +#include "Imports.h" + +#include <ntstrsafe.h> + + +#pragma alloc_text(PAGE, CheckVersion) +#pragma alloc_text(PAGE, GetKernelBase) +#pragma alloc_text(PAGE, RandomMemory32) + +PVOID g_KernelBase = NULL; +ULONG g_KernelSize = 0; + +NTSTATUS CheckVersion(void) +{ + NTSTATUS status; + RTL_OSVERSIONINFOW osver = { 0 }; + + status = RtlGetVersion(&osver); + + if (NT_SUCCESS(status)) + { + KDBG("Os version........: %d.%d.%d", + osver.dwMajorVersion, + osver.dwMinorVersion, + osver.dwBuildNumber); + + if (osver.dwMajorVersion != 10 || + osver.dwMinorVersion != 0 || + osver.dwBuildNumber != 17134) + { + /* TODO: Verify on other builds */ + KDBG("WARNING: ONLY Windows 10.0.17134 (1803/RS4) supported at the moment!\n"); + return STATUS_ACCESS_DENIED; + } + } + + return status; +} + +PVOID GetKernelBase(OUT PULONG pSize) +{ + NTSTATUS status = STATUS_SUCCESS; + ULONG bytes = 0; + PRTL_PROCESS_MODULES pMods = NULL; + PVOID checkPtr = NULL; + UNICODE_STRING routineName; + + // Already found + if (g_KernelBase != NULL) + { + if (pSize) + *pSize = g_KernelSize; + return g_KernelBase; + } + + RtlUnicodeStringInit(&routineName, L"NtOpenFile"); + + checkPtr = MmGetSystemRoutineAddress(&routineName); + if (checkPtr == NULL) + return NULL; + + // Protect from UserMode AV + status = ZwQuerySystemInformation(SystemModuleInformation, 0, bytes, &bytes); + if (bytes == 0) + { + KDBG("Invalid SystemModuleInformation size\n"); + return NULL; + } + + pMods = (PRTL_PROCESS_MODULES)ExAllocatePoolWithTag(NonPagedPool, bytes, PASTDSE_POOL_TAG); + RtlZeroMemory(pMods, bytes); + + status = ZwQuerySystemInformation(SystemModuleInformation, pMods, bytes, &bytes); + + if (NT_SUCCESS(status)) + { + PRTL_PROCESS_MODULE_INFORMATION pMod = pMods->Modules; + + for (ULONG i = 0; i < pMods->NumberOfModules; i++) + { + // System routine is inside module + if (checkPtr >= pMod[i].ImageBase && + checkPtr < (PVOID)((PUCHAR)pMod[i].ImageBase + pMod[i].ImageSize)) + { + g_KernelBase = pMod[i].ImageBase; + g_KernelSize = pMod[i].ImageSize; + if (pSize) + *pSize = g_KernelSize; + break; + } + } + } + + if (pMods) + ExFreePoolWithTag(pMods, PASTDSE_POOL_TAG); + + return g_KernelBase; +} + +NTSTATUS RandomMemory32(PVOID buf, SIZE_T siz) +{ + PUINT32 ptr = (PUINT32)buf; + SIZE_T i; + ULONG seed = RtlRandomEx(buf); + + if (siz < 4) + return STATUS_INFO_LENGTH_MISMATCH; + for (i = 0; i < siz; i += 4) { + ptr[i] = seed; + seed = RtlRandomEx(&seed); + } + ptr[i - 4] = seed; + + return STATUS_SUCCESS; +}
\ No newline at end of file |