注入dll的基本步骤
- CreateToolhelp32Snapshot 获取进程快照取得进程PID
- VirtualAllocEx 申请内存
- WriteProcessMemory 将dll路径写入指定进程的内存
- GetModuleHandle 获取Kernel32基址
- GetProcAddress 获取加载dll 函数地址
- CreateRemoteThread 在目标进程里执行加载dll 函数,将我们的dll注入到目标进程中
#include "framework.h"
#include "WxDemo.h"
#include <TlHelp32.h>
#include <stdio.h>
#include "resource.h"
DWORD ProcessNameFindPID(LPCSTR ProcessName) {
HANDLE allProcess = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
PROCESSENTRY32 processInfo = { 0 };
processInfo.dwSize = sizeof(PROCESSENTRY32);
;
do {
if (strcmp(ProcessName, processInfo.szExeFile) == 0) {
return processInfo.th32ProcessID;
}
} while (Process32Next(allProcess, &processInfo));
}
VOID InjectDll() {
CHAR pathStr[0x100] = { "" };
DWORD pid = ProcessNameFindPID("WeChat.exe");
if (pid == 0) {
MessageBox(NULL, "获取进程id失败", "错误", 0);
return;
}
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
if (NULL == hProcess)
{
MessageBox(NULL, "进程打开失败", "错误", 0);
return;
}
LPVOID dllAdress = VirtualAllocEx(hProcess, NULL, sizeof(pathStr), MEM_COMMIT, PAGE_READWRITE);
if (NULL == dllAdress)
{
MessageBox(NULL, "内存分配失败", "错误", 0);
return;
}
if (WriteProcessMemory(hProcess, dllAdress, pathStr, strlen(pathStr), NULL) == 0)
{
MessageBox(NULL, "dll路径写入失败", "错误", 0);
return;
}
HMODULE kernel32Adr = GetModuleHandle("Kernel32.dll");
LPVOID loadLibraryAdr = GetProcAddress(kernel32Adr, "LoadLibraryA");
HANDLE h = CreateRemoteThread(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)loadLibraryAdr, dllAdress, 0, NULL);
if (NULL == h)
{
MessageBox(NULL, "dll路径写入失败", "错误", 0);
return;
}
}
INT_PTR CALLBACK Dlgproc(
HWND hDlg,
UINT message,
WPARAM param1,
LPARAM param2
) {
switch (message)
{
case WM_INITDIALOG: {
MessageBox(NULL, "首次加载", "标题", 0);
break;
}
case WM_CLOSE: {
EndDialog(hDlg, 0);
}
case WM_COMMAND: {
if (InjectOK==param1) {
}
if (InjectClose == param1)
{
}
break;
}
}
return 0;
}
int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPWSTR lpCmdLine,
_In_ int nCmdShow)
{
DialogBox(hInstance, MAKEINTRESOURCE(ID_MAIN), NULL, &Dlgproc);
return 0;
}
差点被气死, if (WriteProcessMemory(hProcess, dllAdress, pathStr, strlen(pathStr), NULL) == 0)后面不小心加了个分号,一时还看不出来,始终是返回失败,实际上是成功,只不过分号导致判断没啥用,导致直接进入代码块return了,哎,真是一个大坑
|