对内核代码任意位置hook编写 (内联HOOK inline hook)
- #include "ntddk.h"
- #define PAGEDCODE code_seg("PAGE")
- #define LOCKEDCODE code_seg()
- #define INITCODE code_seg("INIT")
- #define PAGEDDATA data_seg("PAGE")
- #define LOCKEDDATA data_seg()
- #define INITDATA data_seg("INIT")
- #pragma pack(1)
- typedef struct ServiceDescriptorEntry {
- unsigned int *ServiceTableBase;
- unsigned int *ServiceCounterTableBase; //仅适用于checked build版本
- unsigned int NumberOfServices;
- unsigned char *ParamTableBase;
- } ServiceDescriptorTableEntry_t, *PServiceDescriptorTableEntry_t;
- #pragma pack()
- __declspec (dllimport) ServiceDescriptorTableEntry_t KeServiceDescriptorTable;
- void PageProtectOn()
- {
- //恢复内存保护
- __asm
- {
- mov eax, cr0
- or eax, 10000h
- mov cr0, eax
- sti
- }
- }
- void PageProtectOff()
- {
- //去掉内存保护
- __asm
- {
- cli
- mov eax, cr0
- and eax, not 10000h
- mov cr0, eax
- }
- }
- ULONG g_ntOpenKey;
- ULONG g_jmp_origNtOpenKey;
- UCHAR g_orig_funcode[5];
- void FilterNtOpenKey()
- {
- KdPrint(("%s\n", (char*)PsGetCurrentProcess() + 0x174));
- }
- __declspec(naked) void NewOpenKey()
- {
- __asm
- {
- pushad
- call FilterNtOpenKey
- popad
- pop eax
- push 0x94
- jmp g_jmp_origNtOpenKey
- }
- }
- #pragma PAGEDCODE
- void HookNtOpenKey()
- {
- ULONG u_jmp_temp;
- UCHAR jmp_code[5];
- g_ntOpenKey = KeServiceDescriptorTable.ServiceTableBase[119];
- g_jmp_origNtOpenKey = g_ntOpenKey + 5;
- u_jmp_temp = (ULONG)NewOpenKey - g_ntOpenKey - 5;
- jmp_code[0] = 0xe8;
- *(ULONG *)&jmp_code[1] = u_jmp_temp;
- PageProtectOff();
- RtlCopyMemory(g_orig_funcode, (PVOID)g_ntOpenKey, 5);
- RtlCopyMemory((PVOID)g_ntOpenKey, jmp_code, 5);
- PageProtectOn();
- }
- #pragma PAGEDCODE
- void UnHookOpenKey()
- {
- PageProtectOff();
- RtlCopyMemory((PVOID)g_ntOpenKey, g_orig_funcode, 5);
- PageProtectOn();
- }
- #pragma PAGEDCODE
- VOID MyDriverUnload(IN PDRIVER_OBJECT pDriverObject)
- {
- UnHookOpenKey();
- KdPrint(("DriverEntry unLoading...\n"));
- }
- #pragma INITCODE
- NTSTATUS DriverEntry(IN PDRIVER_OBJECT pDriverObject, IN PUNICODE_STRING RegistryPath)
- {
- NTSTATUS status = STATUS_SUCCESS;
- HookNtOpenKey();
- pDriverObject->DriverUnload = MyDriverUnload;
- return status;
- }
复制代码 |