PE结构
1、在exe文件中指明了我们需要使用到的dll,和所用到的dll中的哪一些函数。
2、开始DOS头
3、所有的东西都是关于首地址的偏移。
int WINAPI MyMessageBoxW( _In_opt_ HWND hWnd, _In_opt_ LPCTSTR lpText, _In_opt_ LPCTSTR lpCaption, _In_ UINT uType ) { printf("MyMessageBoxW ! ! !"); return 0; } bool setHook() { HMODULE hModule = GetModuleHandle(nullptr); IMAGE_DOS_HEADER * dosHeader = (IMAGE_DOS_HEADER *)hModule; IMAGE_OPTIONAL_HEADER * optionHeader = (IMAGE_OPTIONAL_HEADER *) ((BYTE *)hModule + dosHeader->e_lfanew + sizeof(IMAGE_NT_HEADERS)-sizeof(IMAGE_OPTIONAL_HEADER) ); IMAGE_IMPORT_DESCRIPTOR * importDescriptor = (IMAGE_IMPORT_DESCRIPTOR *)((BYTE *)hModule + optionHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress); while (importDescriptor->FirstThunk) { char * dllName = (char *)((BYTE *)hModule + importDescriptor->Name); if (strcmp(dllName ,"USER32.dll") == 0) { break; } importDescriptor++; } if (importDescriptor->FirstThunk) { DWORD dwFuncAddr = (DWORD)MessageBoxW; IMAGE_THUNK_DATA * thunkData = (IMAGE_THUNK_DATA *)((BYTE *)hModule + importDescriptor->FirstThunk); while (thunkData->u1.Function) { if (thunkData->u1.Function == dwFuncAddr) { DWORD * lpAddr = &(thunkData->u1.Function); DWORD dwOldProtect; MEMORY_BASIC_INFORMATION mbi; VirtualQuery(lpAddr, &mbi, sizeof(mbi)); VirtualProtect(lpAddr, sizeof(DWORD), PAGE_READWRITE, &dwOldProtect); thunkData->u1.Function = (DWORD)MyMessageBoxW; VirtualProtect(lpAddr, sizeof(DWORD), dwOldProtect, nullptr); return true; } thunkData++; } } }
4、文件标志