驅動開發:核心掃描SSDT掛鉤狀態

2023-06-06 09:00:44

在筆者上一篇文章《驅動開發:核心實現SSDT掛鉤與摘鉤》中介紹瞭如何對SSDT函數進行Hook掛鉤與摘鉤的,本章將繼續實現一個新功能,如何檢測SSDT函數是否掛鉤,要實現檢測掛鉤狀態有兩種方式,第一種方式則是類似於《驅動開發:摘除InlineHook核心勾點》文章中所演示的通過讀取函數的前16個位元組與原始位元組做對比來判斷掛鉤狀態,另一種方式則是通過對比函數的當前地址起源地址進行判斷,為了提高檢測準確性本章將採用兩種方式混合檢測。

具體原理,通過解析核心檔案PE結構找到匯出表,依次計算出每一個核心函數的RVA相對偏移,通過與核心模組基址相加此相對偏移得到函數的原始地址,然後再動態獲取函數當前地址,兩者作比較即可得知指定核心函數是否被掛鉤。

在實現這個功能之前我們需要解決兩個問題,第一個問題是如何得到特定核心模組的記憶體模組基址此處我們需要封裝一個GetOsBaseAddress()使用者只需要傳入指定的核心模組即可得到該模組基址,如此簡單的程式碼沒有任何解釋的必要;

// 署名權
// right to sign one's name on a piece of work
// PowerBy: LyShark
// Email: [email protected]

#include <ntifs.h>
#include <ntimage.h>
#include <ntstrsafe.h>

typedef struct _LDR_DATA_TABLE_ENTRY
{
	LIST_ENTRY InLoadOrderLinks;
	LIST_ENTRY InMemoryOrderLinks;
	LIST_ENTRY InInitializationOrderLinks;
	PVOID DllBase;
	PVOID EntryPoint;
	ULONG SizeOfImage;
	UNICODE_STRING FullDllName;
	UNICODE_STRING BaseDllName;
	ULONG Flags;
	USHORT LoadCount;
	USHORT TlsIndex;
	LIST_ENTRY HashLinks;
	ULONG TimeDateStamp;
} LDR_DATA_TABLE_ENTRY, *PLDR_DATA_TABLE_ENTRY;

// 得到核心模組基址
ULONGLONG GetOsBaseAddress(PDRIVER_OBJECT pDriverObject, WCHAR *wzData)
{
	UNICODE_STRING osName = { 0 };
	// WCHAR wzData[0x100] = L"ntoskrnl.exe";
	RtlInitUnicodeString(&osName, wzData);

	LDR_DATA_TABLE_ENTRY *pDataTableEntry, *pTempDataTableEntry;
	//雙迴圈連結串列定義
	PLIST_ENTRY    pList;
	//指向驅動物件的DriverSection
	pDataTableEntry = (LDR_DATA_TABLE_ENTRY*)pDriverObject->DriverSection;
	//判斷是否為空
	if (!pDataTableEntry)
	{
		return 0;
	}

	//得到連結串列地址
	pList = pDataTableEntry->InLoadOrderLinks.Flink;

	// 判斷是否等於頭部
	while (pList != &pDataTableEntry->InLoadOrderLinks)
	{
		pTempDataTableEntry = (LDR_DATA_TABLE_ENTRY *)pList;
		if (RtlEqualUnicodeString(&pTempDataTableEntry->BaseDllName, &osName, TRUE))
		{
			return (ULONGLONG)pTempDataTableEntry->DllBase;
		}
		pList = pList->Flink;
	}
	return 0;
}

VOID UnDriver(PDRIVER_OBJECT driver)
{
	DbgPrint("驅動解除安裝 \n");
}

NTSTATUS DriverEntry(IN PDRIVER_OBJECT Driver, PUNICODE_STRING RegistryPath)
{
	DbgPrint("Hello LyShark.com \n");

	ULONGLONG kernel_base = GetOsBaseAddress(Driver, L"ntoskrnl.exe");
	DbgPrint("ntoskrnl.exe => 模組基址: %p \n", kernel_base);

	ULONGLONG hal_base = GetOsBaseAddress(Driver, L"hal.dll");
	DbgPrint("hal.dll => 模組基址: %p \n", hal_base);

	Driver->DriverUnload = UnDriver;
	return STATUS_SUCCESS;
}

如上直接編譯並執行,即可輸出ntoskrnl.exe以及hal.dll兩個核心模組的基址;

其次我們還需要實現另一個功能,此時想像一下當我告訴你一個記憶體地址,我想要查該記憶體地址屬於哪個模組該如何實現,其實很簡單隻需要拿到這個地址依次去判斷其是否大於等於該模組的基地址,並小於等於該模組的結束地址,那麼我們就認為該地址落在了此模組上,在這個思路下LyShark實現了以下程式碼片段。

// 署名權
// right to sign one's name on a piece of work
// PowerBy: LyShark
// Email: [email protected]

#include <ntifs.h>
#include <ntimage.h>
#include <ntstrsafe.h>

typedef struct _LDR_DATA_TABLE_ENTRY
{
	LIST_ENTRY InLoadOrderLinks;
	LIST_ENTRY InMemoryOrderLinks;
	LIST_ENTRY InInitializationOrderLinks;
	PVOID DllBase;
	PVOID EntryPoint;
	ULONG SizeOfImage;
	UNICODE_STRING FullDllName;
	UNICODE_STRING BaseDllName;
	ULONG Flags;
	USHORT LoadCount;
	USHORT TlsIndex;
	LIST_ENTRY HashLinks;
	ULONG TimeDateStamp;
} LDR_DATA_TABLE_ENTRY, *PLDR_DATA_TABLE_ENTRY;

// 掃描指定地址是否在某個模組內
VOID ScanKernelModuleBase(PDRIVER_OBJECT pDriverObject, ULONGLONG address)
{
	LDR_DATA_TABLE_ENTRY *pDataTableEntry, *pTempDataTableEntry;
	PLIST_ENTRY pList;
	pDataTableEntry = (LDR_DATA_TABLE_ENTRY*)pDriverObject->DriverSection;
	if (!pDataTableEntry)
	{
		return;
	}

	// 得到連結串列地址
	pList = pDataTableEntry->InLoadOrderLinks.Flink;

	// 判斷是否等於頭部
	while (pList != &pDataTableEntry->InLoadOrderLinks)
	{
		pTempDataTableEntry = (LDR_DATA_TABLE_ENTRY *)pList;

		ULONGLONG start_address = (ULONGLONG)pTempDataTableEntry->DllBase;
		ULONGLONG end_address = start_address + (ULONG)pTempDataTableEntry->SizeOfImage;

		// 判斷區間
		// DbgPrint("起始地址 [ %p ] 結束地址 [ %p ] \n",start_address,end_address);
		if (address >= start_address && address <= end_address)
		{
			DbgPrint("[LyShark] 當前函數所在模組 [ %ws ] \n", (CHAR *)pTempDataTableEntry->FullDllName.Buffer);
		}
		pList = pList->Flink;
	}
}

VOID UnDriver(PDRIVER_OBJECT driver)
{
	DbgPrint("驅動解除安裝 \n");
}

NTSTATUS DriverEntry(IN PDRIVER_OBJECT Driver, PUNICODE_STRING RegistryPath)
{
	DbgPrint("Hello LyShark.com \n");

	ScanKernelModuleBase(Driver, 0xFFFFF8051AF5D030);

	Driver->DriverUnload = UnDriver;
	return STATUS_SUCCESS;
}

我們以0xFFFFF8051AF5D030地址為例對其進行判斷可看到輸出瞭如下結果,此地址被落在了hal.dll模組上;

為了能讀入磁碟PE檔案到記憶體此時我們還需要封裝一個LoadKernelFile()函數,該函數的作用是讀入一個核心檔案到記憶體空間中,此處如果您使用前一篇《驅動開發:核心解析PE結構匯出表》文章中的記憶體對映函數來讀寫則會藍屏,原因很簡單KernelMapFile()是對映而對映一定無法一次性完整裝載其次此方法本質上還在佔用原檔案,而LoadKernelFile()則是讀取磁碟檔案並將其完整拷貝一份,這是兩者的本質區別,如下程式碼則是實現完整拷貝的實現;

// 署名權
// right to sign one's name on a piece of work
// PowerBy: LyShark
// Email: [email protected]

#include <ntifs.h>
#include <ntimage.h>
#include <ntstrsafe.h>

// 將核心檔案裝載入記憶體(磁碟)
PVOID LoadKernelFile(WCHAR *wzFileName)
{
	NTSTATUS Status;
	HANDLE FileHandle;
	IO_STATUS_BLOCK ioStatus;
	FILE_STANDARD_INFORMATION FileInformation;

	// 設定路徑
	UNICODE_STRING uniFileName;
	RtlInitUnicodeString(&uniFileName, wzFileName);

	// 初始化開啟檔案的屬性
	OBJECT_ATTRIBUTES objectAttributes;
	InitializeObjectAttributes(&objectAttributes, &uniFileName, OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE, NULL, NULL);

	// 開啟檔案
	Status = IoCreateFile(&FileHandle, FILE_READ_ATTRIBUTES | SYNCHRONIZE, &objectAttributes, &ioStatus, 0, FILE_READ_ATTRIBUTES, FILE_SHARE_READ, FILE_OPEN, FILE_SYNCHRONOUS_IO_NONALERT, NULL, 0, CreateFileTypeNone, NULL, IO_NO_PARAMETER_CHECKING);
	if (!NT_SUCCESS(Status))
	{
		return 0;
	}

	// 獲取檔案資訊
	Status = ZwQueryInformationFile(FileHandle, &ioStatus, &FileInformation, sizeof(FILE_STANDARD_INFORMATION), FileStandardInformation);
	if (!NT_SUCCESS(Status))
	{
		ZwClose(FileHandle);
		return 0;
	}

	// 判斷檔案大小是否過大
	if (FileInformation.EndOfFile.HighPart != 0)
	{
		ZwClose(FileHandle);
		return 0;
	}

	// 取檔案大小
	ULONG64 uFileSize = FileInformation.EndOfFile.LowPart;

	// 分配記憶體
	PVOID pBuffer = ExAllocatePoolWithTag(NonPagedPool, uFileSize + 0x100, (ULONG)"LyShark");
	if (pBuffer == NULL)
	{
		ZwClose(FileHandle);
		return 0;
	}

	// 從頭開始讀取檔案
	LARGE_INTEGER byteOffset;
	byteOffset.LowPart = 0;
	byteOffset.HighPart = 0;
	Status = ZwReadFile(FileHandle, NULL, NULL, NULL, &ioStatus, pBuffer, uFileSize, &byteOffset, NULL);
	if (!NT_SUCCESS(Status))
	{
		ZwClose(FileHandle);
		return 0;
	}

	// ExFreePoolWithTag(pBuffer, (ULONG)"LyShark");
	ZwClose(FileHandle);
	return pBuffer;
}

VOID UnDriver(PDRIVER_OBJECT driver)
{
	DbgPrint("驅動解除安裝 \n");
}

NTSTATUS DriverEntry(IN PDRIVER_OBJECT Driver, PUNICODE_STRING RegistryPath)
{
	// 載入核心模組
	PVOID BaseAddress = LoadKernelFile(L"\\SystemRoot\\system32\\ntoskrnl.exe");
	DbgPrint("BaseAddress = %p\n", BaseAddress);

	// 解析PE頭
	PIMAGE_DOS_HEADER pDosHeader;
	PIMAGE_NT_HEADERS pNtHeaders;

	// DLL記憶體資料轉成DOS頭結構
	pDosHeader = (PIMAGE_DOS_HEADER)BaseAddress;

	// 取出PE頭結構
	pNtHeaders = (PIMAGE_NT_HEADERS)((ULONGLONG)BaseAddress + pDosHeader->e_lfanew);

	DbgPrint("[LyShark] => 映像基址: %p \n", pNtHeaders->OptionalHeader.ImageBase);

	// 結束後釋放記憶體
	ExFreePoolWithTag(BaseAddress, (ULONG)"LyShark");

	Driver->DriverUnload = UnDriver;
	return STATUS_SUCCESS;
}

執行如上這段程式,則會將ntoskrnl.exe檔案載入到記憶體,並讀取出其中的OptionalHeader.ImageBase映像基址,如下圖所示;

有了上述方法,最後一步就是組合並實現判斷即可,如下程式碼通過對匯出表的解析,並過濾出所有的Nt開頭的系列函數,然後依次對比起源地址與原地址是否一致,得出是否被掛鉤,完整程式碼如下所示;

// 署名權
// right to sign one's name on a piece of work
// PowerBy: LyShark
// Email: [email protected]

ULONGLONG ntoskrnl_base = 0;

NTSTATUS DriverEntry(IN PDRIVER_OBJECT Driver, PUNICODE_STRING RegistryPath)
{
	DbgPrint("Hello LyShark.com \n");

	// 載入核心模組
	PVOID BaseAddress = LoadKernelFile(L"\\SystemRoot\\system32\\ntoskrnl.exe");
	DbgPrint("BaseAddress = %p\n", BaseAddress);

	// 獲取核心模組地址
	ntoskrnl_base = GetOsBaseAddress(Driver, L"ntoskrnl.exe");

	// 取出匯出表
	PIMAGE_DOS_HEADER pDosHeader;
	PIMAGE_NT_HEADERS pNtHeaders;
	PIMAGE_SECTION_HEADER pSectionHeader;
	ULONGLONG FileOffset;
	PIMAGE_EXPORT_DIRECTORY pExportDirectory;

	// DLL記憶體資料轉成DOS頭結構
	pDosHeader = (PIMAGE_DOS_HEADER)BaseAddress;
	// 取出PE頭結構
	pNtHeaders = (PIMAGE_NT_HEADERS)((ULONGLONG)BaseAddress + pDosHeader->e_lfanew);
	// 判斷PE頭匯出表表是否為空
	if (pNtHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress == 0)
	{
		return 0;
	}

	// 取出匯出表偏移
	FileOffset = pNtHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;

	// 取出節頭結構
	pSectionHeader = (PIMAGE_SECTION_HEADER)((ULONGLONG)pNtHeaders + sizeof(IMAGE_NT_HEADERS));
	PIMAGE_SECTION_HEADER pOldSectionHeader = pSectionHeader;

	// 遍歷節結構進行地址運算
	for (UINT16 Index = 0; Index < pNtHeaders->FileHeader.NumberOfSections; Index++, pSectionHeader++)
	{
		if (pSectionHeader->VirtualAddress <= FileOffset && FileOffset <= pSectionHeader->VirtualAddress + pSectionHeader->SizeOfRawData)
		{
			FileOffset = FileOffset - pSectionHeader->VirtualAddress + pSectionHeader->PointerToRawData;
		}
	}

	// 匯出表地址
	pExportDirectory = (PIMAGE_EXPORT_DIRECTORY)((ULONGLONG)BaseAddress + FileOffset);

	// 取出匯出表函數地址
	PULONG AddressOfFunctions;
	FileOffset = pExportDirectory->AddressOfFunctions;

	// 遍歷節結構進行地址運算
	pSectionHeader = pOldSectionHeader;
	for (UINT16 Index = 0; Index < pNtHeaders->FileHeader.NumberOfSections; Index++, pSectionHeader++)
	{
		if (pSectionHeader->VirtualAddress <= FileOffset && FileOffset <= pSectionHeader->VirtualAddress + pSectionHeader->SizeOfRawData)
		{
			FileOffset = FileOffset - pSectionHeader->VirtualAddress + pSectionHeader->PointerToRawData;
		}
	}

	// 這裡注意一下foa和rva
	AddressOfFunctions = (PULONG)((ULONGLONG)BaseAddress + FileOffset);

	// 取出匯出表函數名字
	PUSHORT AddressOfNameOrdinals;
	FileOffset = pExportDirectory->AddressOfNameOrdinals;

	// 遍歷節結構進行地址運算
	pSectionHeader = pOldSectionHeader;
	for (UINT16 Index = 0; Index < pNtHeaders->FileHeader.NumberOfSections; Index++, pSectionHeader++)
	{
		if (pSectionHeader->VirtualAddress <= FileOffset && FileOffset <= pSectionHeader->VirtualAddress + pSectionHeader->SizeOfRawData)
		{
			FileOffset = FileOffset - pSectionHeader->VirtualAddress + pSectionHeader->PointerToRawData;
		}
	}

	// 注意一下foa和rva
	AddressOfNameOrdinals = (PUSHORT)((ULONGLONG)BaseAddress + FileOffset);

	// 取出匯出表函數序號
	PULONG AddressOfNames;
	FileOffset = pExportDirectory->AddressOfNames;

	// 遍歷節結構進行地址運算
	pSectionHeader = pOldSectionHeader;
	for (UINT16 Index = 0; Index < pNtHeaders->FileHeader.NumberOfSections; Index++, pSectionHeader++)
	{
		if (pSectionHeader->VirtualAddress <= FileOffset && FileOffset <= pSectionHeader->VirtualAddress + pSectionHeader->SizeOfRawData)
		{
			FileOffset = FileOffset - pSectionHeader->VirtualAddress + pSectionHeader->PointerToRawData;
		}
	}

	// 注意一下foa和rva
	AddressOfNames = (PULONG)((ULONGLONG)BaseAddress + FileOffset);

	// 分析匯出表
	ULONG uOffset;
	LPSTR FunName;
	ULONG uAddressOfNames;
	ULONG TargetOff = 0;

	for (ULONG uIndex = 0; uIndex < pExportDirectory->NumberOfNames; uIndex++, AddressOfNames++, AddressOfNameOrdinals++)
	{
		uAddressOfNames = *AddressOfNames;
		pSectionHeader = pOldSectionHeader;
		for (UINT16 Index = 0; Index < pNtHeaders->FileHeader.NumberOfSections; Index++, pSectionHeader++)
		{
			if (pSectionHeader->VirtualAddress <= uAddressOfNames && uAddressOfNames <= pSectionHeader->VirtualAddress + pSectionHeader->SizeOfRawData)
			{
				uOffset = uAddressOfNames - pSectionHeader->VirtualAddress + pSectionHeader->PointerToRawData;
			}
		}
		FunName = (LPSTR)((ULONGLONG)BaseAddress + uOffset);

		if (FunName[0] == 'N' && FunName[1] == 't')
		{
			// 得到相對RVA
			TargetOff = (ULONG)AddressOfFunctions[*AddressOfNameOrdinals];

			// LPSTR -> UNCODE
			// 先轉成ANSI 然後在轉成 UNCODE
			ANSI_STRING ansi = { 0 };
			UNICODE_STRING uncode = { 0 };

			RtlInitAnsiString(&ansi, FunName);
			RtlAnsiStringToUnicodeString(&uncode, &ansi, TRUE);

			// 得到當前地址
			PULONGLONG local_address = MmGetSystemRoutineAddress(&uncode);

			/*
			// 讀入核心函數前6個位元組
			unsigned char local_opcode[6] = { 0 };
			unsigned char this_opcode[6] = { 0 };

			RtlCopyMemory(local_opcode, (void *)local_address, 6);
			RtlCopyMemory(this_opcode, (void *)(ntoskrnl_base + TargetOff), 6);

			// 當前機器碼
			for (int x = 0; x < 6; x++)
			{
			DbgPrint("當前 [ %d ] 機器碼 [ %x ] ", x, local_opcode[x]);
			}

			// 起源機器碼
			for (int y = 0; y < 6; y++)
			{
			DbgPrint("起源 [ %d ] 機器碼 [ %x ] ", y, this_opcode[y]);
			}

			*/

			// 檢測是否被掛鉤 [不相等則說明被掛鉤了]
			if (local_address != (ntoskrnl_base + TargetOff))
			{
				DbgPrint("索引 [ %d ] RVA [ %p ] \n --> 起源地址 [ %p ] | 當前地址 [ %p ] | 函數名 [ %s ] \n\n",
					*AddressOfNameOrdinals, TargetOff, ntoskrnl_base + TargetOff, local_address, FunName);
			}

			// 檢查當前地址所在模組
			// ScanKernelModuleBase(Driver, (PULONGLONG)local_address);
		}
	}

	// 結束後釋放記憶體
	ExFreePoolWithTag(BaseAddress, (ULONG)"LyShark");

	Driver->DriverUnload = UnDriver;
	return STATUS_SUCCESS;
}

使用ARK工具手動改寫幾個Nt開頭的函數,並執行這段程式碼,觀察是否可以輸出被掛鉤的函數詳情;