|
#include <Windows.h>
#include <stdio.h>
// 要Hook的函数
void targetFunction() {
printf("原始函数被调用\n");
}
// 替换后的函数
void hookedFunction() {
printf("Hooked函数被调用\n");
}
// 注入DLL并Hook指定函数
void injectAndHook(DWORD processId) {
// 1. 打开进程
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, processId);
if (hProcess == NULL) {
printf("无法打开进程\n");
return;
}
// 2. 为Hook函数分配内存
LPVOID remoteFunc = VirtualAllocEx(hProcess, NULL, 1024, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
if (remoteFunc == NULL) {
printf("无法在目标进程分配内存\n");
CloseHandle(hProcess);
return;
}
// 3. 写入Hook函数的机器码
unsigned char shellCode[1024];
DWORD size = sizeof(shellCode);
DWORD bytesWritten;
if (!GetHookCode(hookedFunction, (PBYTE)targetFunction, shellCode, &size)) {
printf("无法生成Hook代码\n");
VirtualFreeEx(hProcess, remoteFunc, 1024, MEM_RELEASE);
CloseHandle(hProcess);
return;
}
if (!WriteProcessMemory(hProcess, remoteFunc, shellCode, size, &bytesWritten)) {
printf("无法写入Hook代码到目标进程\n");
VirtualFreeEx(hProcess, remoteFunc, 1024, MEM_RELEASE);
CloseHandle(hProcess);
return;
}
// 4. 找到要Hook的函数地址
LPVOID funcAddress = (LPVOID)(DWORD)GetModuleHandle(NULL) + (DWORD)&targetFunction - (DWORD)GetModuleHandle(NULL);
if (funcAddress == NULL) {
printf("无法获取函数地址\n");
VirtualFreeEx(hProcess, remoteFunc, 1024, MEM_RELEASE);
CloseHandle(hProcess);
return;
}
// 5. 修改原函数的第一条指令为跳转到我们的Hook函数
DWORD oldProtect;
if (!VirtualProtectEx(hProcess, funcAddress, 5, PAGE_EXECUTE_READWRITE, &oldProtect)) {
printf("无法修改内存属性\n");
VirtualFreeEx(hProcess, remoteFunc, 1024, MEM_RELEASE);
CloseHandle(hProcess);
return;
}
BYTE jumpCode[5] = { 0xE9 }; // 近跳转指令
*(DWORD*)(jumpCode + 1) = (DWORD)remoteFunc - (DWORD)funcAddress - 5;
if (!WriteProcessMemory(hProcess, funcAddress, jumpCode, 5, &bytesWritten)) {
printf("无法写入Hook代码\n");
VirtualProtectEx(hProcess, funcAddress, 5, oldProtect, &oldProtect);
VirtualFreeEx(hProcess, remoteFunc, 1024, MEM_RELEASE);
CloseHandle(hProcess);
return;
}
VirtualProtectEx(hProcess, funcAddress, 5, oldProtect, &oldProtect);
CloseHandle(hProcess);
}
//
|
|