#include <stdio.h>
#include <stddef.h>
#include <windows.h>
#pragma comment(lib, "ImageHlp.lib")
#pragma pack (push ,1) //以下结构字节对齐
typedef struct
{
BYTE int_PUSHAD;
BYTE int_PUSH;
DWORD push_Value;
BYTE int_MOVEAX;
DWORD eax_Value;
WORD call_eax;
BYTE jmp_MOVEAX;
DWORD jmp_Value;
WORD jmp_eax;
char szDLL[MAX_PATH];
}INJECT_LOADLIBRARY_CODE, *LPINJECT_CODE, INJECT_CODE;
#pragma pack (pop , 1)
typedef struct
{
LPBYTE lpEntryPoint; // 目标进程的入口地址
BYTE oldcode[sizeof(INJECT_CODE)];// 目标进程的代码保存
}SPY_MEM_SHARE, * LPSPY_MEM_SHARE;
typedef struct
{
DWORD lpEntryPoint;
DWORD OldAddr;
DWORD OldCode[4];
}JMP_CODE, *LPJMP_CODE;
static JMP_CODE _lpCode;
//跳到目标进程入口地址
void __declspec(naked)DoJmpEntryPoint()
{
DWORD *_glpMovEax;
WORD *_GlpJmp;
DWORD _gfNew;
DWORD _gfOld;
// 恢复LoadLibrary后面的代码
_gfNew = PAGE_READWRITE;
_glpMovEax = (DWORD*)_lpCode.OldAddr;
VirtualProtect(_glpMovEax, 2*sizeof(DWORD), _gfNew, &_gfOld);
*_glpMovEax = _lpCode.OldCode[0];
*(_glpMovEax + 1) = _lpCode.OldCode[1];
VirtualProtect(_glpMovEax, 2*sizeof(DWORD), _gfOld, &_gfNew);
// 跳至目标代码的入口
_asm popad
_asm jmp _lpCode.lpEntryPoint
}
BOOL WINAPI InitApiSpy()
{
HANDLE hMap;
LPSPY_MEM_SHARE lpMem;
DWORD dwSize;
BOOL rc;
BYTE *lpByte;
// 取得FileMapping的句柄
hMap = OpenFileMapping(FILE_MAP_ALL_ACCESS, 0, "MyDllMapView");
if(hMap)
{
lpMem = (LPSPY_MEM_SHARE)MapViewOfFile(hMap, FILE_MAP_ALL_ACCESS, 0, 0, 0);
if(lpMem)
{
// 恢复目标进程的入口代码
// 得到mov eax, value代码的地址
_lpCode.OldAddr = (DWORD)((BYTE*)lpMem->lpEntryPoint + offsetof(INJECT_CODE, jmp_MOVEAX));
_lpCode.lpEntryPoint = (DWORD)lpMem->lpEntryPoint;
// 保存LoadLibrary()后面的代码
memcpy(&_lpCode.OldCode, (BYTE*)lpMem->oldcode + offsetof(INJECT_CODE, jmp_MOVEAX), 2*sizeof(DWORD));
// 恢复目标进程的入口代码
rc = WriteProcessMemory(GetCurrentProcess(), lpMem->lpEntryPoint, lpMem->oldcode, sizeof(INJECT_CODE), &dwSize);
lpByte = (BYTE*)lpMem->lpEntryPoint + offsetof(INJECT_CODE, jmp_MOVEAX);
UnmapViewOfFile(lpMem);
}
CloseHandle(hMap);
}
BYTE *lpMovEax;
DWORD *lpMovEaxValu;
WORD *lpJmp;
DWORD fNew;
DWORD fOld;
fNew = PAGE_READWRITE;
lpMovEax = lpByte;
VirtualProtect(lpMovEax, 2*sizeof(DWORD), fNew, &fOld);
*lpMovEax = 0xB8;
lpMovEaxValu = (DWORD*)(lpMovEax + 1);
*lpMovEaxValu = (DWORD)&DoJmpEntryPoint;
lpJmp = (WORD*)(lpMovEax + 5);
*lpJmp = 0xE0FF; // (FF E0)
VirtualProtect(lpMovEax, 2*sizeof(DWORD), fOld, &fNew);
//调用自定义函数,做你想做的事
//MyFunc();
return TRUE;
}
BOOL APIENTRY DllMain( HANDLE hInstance,
DWORD ul_reason_for_call,
LPVOID lpReserved)
{
//MyhModule = (HMODULE)hInstance;
if(ul_reason_for_call == DLL_PROCESS_ATTACH)
return InitApiSpy();
return TRUE;
}