挂起和取消挂起一个文件DLL

Hook and unhook one file DLL

本文关键字:挂起 一个 文件 DLL 取消      更新时间:2023-10-16

我尝试将文件DLL挂接到控制台应用程序中。此代码

#include "pch.h"
#include <vector>
#include <string>
#include <windows.h>
#include <Tlhelp32.h>
using std::vector;
using std::string;
int main(void)
{
while (true)
{
vector<string>processNames;
PROCESSENTRY32 pe32;
pe32.dwSize = sizeof(PROCESSENTRY32);
HANDLE hTool32 = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
BOOL bProcess = Process32First(hTool32, &pe32);
if (bProcess == TRUE)
{
while ((Process32Next(hTool32, &pe32)) == TRUE)
{
processNames.push_back(pe32.szExeFile);
if (strcmp(pe32.szExeFile, "ConsoleApplication4.exe") == 0)
{
char* DirPath = new char[MAX_PATH];
char* FullPath = new char[MAX_PATH];
GetCurrentDirectory(MAX_PATH, DirPath);
sprintf_s(FullPath, MAX_PATH, "%s\..\ConsoleApplication1\ConsoleApplication1.dll", DirPath);
FILE *pFile;
if (fopen_s(&pFile, FullPath, "r") || !pFile)
{
OutputDebugString("[Hook] File name or file does not exist");
OutputDebugString(FullPath);
return -1;
}
fclose(pFile);
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pe32.th32ProcessID);
if (!hProcess)
{
OutputDebugString("[Hook] Open process fail");
return -1;
}
//attach
LPVOID LoadLibraryAddr = (LPVOID)GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA");
if (!LoadLibraryAddr)
{
OutputDebugString("[Hook] Load LoadLibraryA fail");
return -1;
}
LPVOID LLParam = (LPVOID)VirtualAllocEx(hProcess, NULL, strlen(FullPath), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
if (!WriteProcessMemory(hProcess, LLParam, FullPath, strlen(FullPath), NULL))
{
OutputDebugString("[Hook] Write process fail");
return -1;
}
HANDLE hHandle = CreateRemoteThread(hProcess, NULL, NULL, (LPTHREAD_START_ROUTINE)LoadLibraryAddr, LLParam, NULL, NULL);
if (!hHandle)
{
OutputDebugString("[Hook] Hooked fail");
return -1;
}
system("pause");
//detach
LoadLibraryAddr = (LPVOID)GetProcAddress(GetModuleHandle("kernel32.dll"), "FreeLibrary");
if (!LoadLibraryAddr)
{
OutputDebugString("[Hook] Load FreeLibrary fail");
return -1;
}
hHandle = CreateRemoteThread(hProcess, NULL, NULL, (LPTHREAD_START_ROUTINE)LoadLibraryAddr, LLParam, NULL, NULL);
if (!hHandle)
{
OutputDebugString("[Hook] detach fail");
return -1;
}
CloseHandle(hProcess);
delete[] DirPath;
delete[] FullPath;
system("pause");
return 0;
}
}
}
CloseHandle(hTool32);
}
return 0;
}

我对此有一些疑问:-为什么此代码无法分离文件dll?-为什么我更改LoadLibraryA->LoadLibrary:加载LoadLibrary失败?-为什么我更改LoadLibraryA->LoadLibraryW:file dll不附加?-代码在Mutibyte运行是好的,但转换为Unicode,文件dll没有附加?

谢谢,

这在多字节中有效,但不会使用unicode字符集进行编译的原因是,您正在传递一个正则c字符串,该字符串是一个正则char数组。当您将构建类型设置为使用多字节LoadLibrary((时,解析为ansi版本,即LoadLibraryA((。如果您想在项目属性中使用Unicode,它将解析为LoadLibraryW((,并且您需要传递Unicode char数组,通常为wchar_t[]。

即使在unicode模式下编译,您仍然可以调用LoadLibraryA((并传递c字符串,但您必须专门调用函数的a(ansi(版本,而不是依赖于为您解析它们的#ifdef预处理器语句。