文章详情
C++远程线程注入函数(dll注入)
Posted on 2018-02-20 22:56:41 by 主打一个C++
#include <windows.h>
#include <iostream>
// 注入DLL参数:进程ID,DLL路径
int InjectDLL(DWORD processID, const char* dllPath) {
HANDLE hProcess = nullptr;
LPVOID pDllPath = nullptr;
HMODULE hKernel32 = nullptr;
HANDLE hThread = nullptr;
do
{
//打开进程
hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, processID);
if (hProcess == NULL) {
std::cerr << "无法打开进程: " << GetLastError() << std::endl;
break;
}
//分配内存
pDllPath = VirtualAllocEx(hProcess, NULL, strlen(dllPath) + 1, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
if (pDllPath == NULL) {
std::cerr << "无法分配内存: " << GetLastError() << std::endl;
break;
}
if (WriteProcessMemory(hProcess, pDllPath, (LPVOID)dllPath, strlen(dllPath) + 1, NULL) == FALSE) {
std::cerr << "无法写入内存: " << GetLastError() << std::endl;
break;
}
hKernel32 = GetModuleHandleA("kernel32.dll");
if (hKernel32 == nullptr)
{
std::cerr << "无法获取 kernel32.dll 句柄: " << GetLastError() << std::endl;
break;
}
FARPROC pLoadLibrary = GetProcAddress(hKernel32, "LoadLibraryA");
if (pLoadLibrary == nullptr) {
std::cerr << "无法获取 LoadLibraryA 地址: " << GetLastError() << std::endl;
break;
}
hThread = CreateRemoteThread(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)pLoadLibrary, pDllPath, 0, NULL);
if (hThread == NULL) {
std::cerr << "无法创建远程线程: " << GetLastError() << std::endl;
break;
}
WaitForSingleObject(hThread, INFINITE);
} while (false);
if(pDllPath) VirtualFreeEx(hProcess, pDllPath, 0, MEM_RELEASE);
if(hThread) CloseHandle(hThread);
if(hKernel32) FreeLibrary(hKernel32);
if(hProcess) CloseHandle(hProcess);
}
*转载请注明出处:原文链接:https://cpp.vin/page/64.html