WeChatFerry/SDK/injector.cpp

71 lines
2.5 KiB
C++
Raw Normal View History

2022-08-14 07:15:05 +08:00
#include "injector.h"
2021-02-12 23:21:57 +08:00
2022-08-14 07:15:05 +08:00
int InjectDll(DWORD pid, const WCHAR *dllPath)
2021-02-12 23:21:57 +08:00
{
HANDLE hThread;
2022-08-14 07:15:05 +08:00
DWORD dwWriteSize = 0;
// 1. 获取目标进程,并在目标进程的内存里开辟空间
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
LPVOID pRemoteAddress = VirtualAllocEx(hProcess, NULL, 1, MEM_COMMIT, PAGE_READWRITE);
// 2. 把 dll 的路径写入到目标进程的内存空间中
if (pRemoteAddress) {
WriteProcessMemory(hProcess, pRemoteAddress, dllPath, wcslen(dllPath) * 2 + 2, &dwWriteSize);
} else {
MessageBox(NULL, L"DLL 路径写入失败", L"InjectDll", 0);
return -1;
2021-02-12 23:21:57 +08:00
}
2022-08-14 07:15:05 +08:00
// 3. 创建一个远程线程,让目标进程调用 LoadLibrary
hThread = CreateRemoteThread(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)LoadLibrary, pRemoteAddress, NULL, NULL);
if (hThread) {
WaitForSingleObject(hThread, -1);
} else {
MessageBox(NULL, L"LoadLibrary 调用失败", L"InjectDll", 0);
return -2;
2021-02-12 23:21:57 +08:00
}
CloseHandle(hThread);
2022-08-14 07:15:05 +08:00
VirtualFreeEx(hProcess, pRemoteAddress, 0, MEM_RELEASE);
CloseHandle(hProcess);
2021-02-12 23:21:57 +08:00
return 0;
}
2022-08-14 07:15:05 +08:00
int EjectDll(DWORD pid, const WCHAR *dllPath)
2021-02-12 23:21:57 +08:00
{
2022-08-14 07:15:05 +08:00
DWORD dwHandle, dwID;
HANDLE hThread = NULL;
DWORD dwWriteSize = 0;
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
LPVOID pRemoteAddress = VirtualAllocEx(hProcess, NULL, 1, MEM_COMMIT, PAGE_READWRITE);
if (pRemoteAddress)
WriteProcessMemory(hProcess, pRemoteAddress, dllPath, wcslen(dllPath) * 2 + 2, &dwWriteSize);
else {
MessageBox(NULL, L"DLL 路径写入失败", L"EjectDll", 0);
return -1;
}
hThread = CreateRemoteThread(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)GetModuleHandleW, pRemoteAddress, 0, &dwID);
if (hThread) {
WaitForSingleObject(hThread, INFINITE);
GetExitCodeThread(hThread, &dwHandle);
2021-02-12 23:21:57 +08:00
} else {
2022-08-14 07:15:05 +08:00
MessageBox(NULL, L"GetModuleHandleW 调用失败!", L"EjectDll", 0);
return -2;
2021-02-12 23:21:57 +08:00
}
2022-08-14 07:15:05 +08:00
CloseHandle(hThread);
2021-02-12 23:21:57 +08:00
2022-08-14 07:15:05 +08:00
// 使目标进程调用 FreeLibrary卸载 DLL
hThread = CreateRemoteThread(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)FreeLibrary, (LPVOID)dwHandle, 0, &dwID);
if (hThread) {
WaitForSingleObject(hThread, INFINITE);
2021-02-12 23:21:57 +08:00
} else {
2022-08-14 07:15:05 +08:00
MessageBox(NULL, L"FreeLibrary 调用失败!", L"EjectDll", 0);
return -3;
2021-02-12 23:21:57 +08:00
}
2022-08-14 07:15:05 +08:00
CloseHandle(hThread);
VirtualFreeEx(hProcess, pRemoteAddress, 0, MEM_RELEASE);
CloseHandle(hProcess);
return 0;
2021-02-12 23:21:57 +08:00
}